Reading multiple character arrays in C using scanf [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash 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.





Don't use scanf. Use fgets and strip of the n if you don't want it
– 4386427
Aug 6 at 14:49



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'

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS