问题
scanf()
always discards white spaces and new line characters. But when I give a character and press enter the new line character is read and stored. I'm unable to read required number of characters because of this. Is there any problem with my code, or some other thing?
The same problem goes with gets. Many posts suggested using fgets()
rather than using the above both but I need to know why is this happening.
回答1:
For %c
the man page says (see http://man7.org/linux/man-pages/man3/scanf.3.html) :
c Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.
Notice the part: The usual skip of leading white space is suppressed.
Also Notice the part: To skip white space first, use an explicit space in the format.
So if you want to skip whites spaces, try adding a space before %c
:
char c;
scanf(" %c", &c);
来源:https://stackoverflow.com/questions/44743789/scanf-is-reading-new-line-character