Reputation: 51
struct Demo{
char a[50];
char b[50];
int a;
};
Can anyone give the code for this structure Demo where a and b will contains string with different words[white-spaces].
I tried
scanf("[^\n]s",name.a); //where name is the object
fgets(name.a,50,stdin);
Note : we can't use gets
method as well
So, If any other method is there, please provide me.
Upvotes: 0
Views: 430
Reputation: 154280
To read a line of user input into char a[50];
with its potential trailing '\n'
trimmed:
if (fgets(name.a, sizeof name.a, stdin)) {
name.a[strcspn(name.a, "\n")] = '\0'; // trim \n
}
Work is needed to cope with consuming excessive long input lines and using the last element of name.a[]
such as:
// Alternative
if (scanf("%49[^\n]", name.a) == 1) {
// consume trailing input
int ch;
while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
;
}
} else { // Handle lines of only \n, end-of-file or input error
name.a[0] = '\0';
}
The scanf("%49[^\n]%*c", name.a)
approach has trouble in 2 cases:
1) The input is only "\n"
, nothing is saved in name.a
and '\n'
remains in stdin
.
2) With input longer than 49 characters (aside from the '\n'
), the %*c
consumes an extra character, yet the rest of the long input line remains in stdin
.
Both of these issues can be solves with additional code too.
Upvotes: 2