scanf is reading new line character

依然范特西╮ 提交于 2019-12-13 22:42:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!