Reading multiple character arrays in C using scanf [duplicate]
Clash Royale CLAN TAG#URR8PPP
Reading multiple character arrays in C using scanf [duplicate]
This question already has an answer here:
char a[100],b[100],c[100];
scanf("%[^n]",a);
printf("%s",a);
scanf("%[^n]",b);
printf("%s",b);
The compiler seems to be reading the first read but skips the second read. Why is this happening?
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
scanf
fgets
n
Or, if you want to use
scanf
, you can consume and discard the newline with scanf("%99[^n]%*c", a);
. (Added 99
to avoid buffer overflow).– Johnny Mopp
Aug 6 at 14:57
scanf
scanf("%99[^n]%*c", a);
99
Tip: When I/O is not working as expected, the 1st line of defense coding is to check the result value of the functions.
int cnt = scanf("%[^n]",b); if (cnt != 1) printf("Unexpected scan %dn", cnt);
would have helped this code a lot to narrow the issue.– chux
Aug 6 at 16:06
int cnt = scanf("%[^n]",b); if (cnt != 1) printf("Unexpected scan %dn", cnt);
1 Answer
1
Because of un handled Enter
Use fgets()
fgets()
Try this :-
char a[100], b[100], c[100];
fgets(a, 100, stdin);
printf("%s", a);
fgets(b, 100, stdin);
printf("%s", b);
Why is that a problem?
– metasj
Aug 6 at 14:50
The
newline
generated in scanning a
is assigned to b
– anoopknr
Aug 6 at 14:53
newline
a
b
Testing the return value of
fgets()
would prevent potential undefined behavior on early end of file.– chqrlie
Aug 6 at 14:58
fgets()
@anoopknr The newline generated in scanning a is assigned to b --> No. with
scanf("%[^n]",b);
, b
would not get a 'n'
assigned.– chux
Aug 6 at 16:08
scanf("%[^n]",b);
b
'n'
Don't use
scanf
. Usefgets
and strip of then
if you don't want it– 4386427
Aug 6 at 14:49