scanf正在读取新行字符

时间:2017-06-25 06:26:12

标签: c++ newline scanf

scanf()始终会丢弃空格和换行符。但是当我给出一个角色并按下输入时,新行字符被读取并存储。因为这个原因,我无法读取所需数量的字符。我的代码或其他东西有问题吗?

同样的问题与获取。许多帖子建议使用fgets()而不是使用上述两者,但我需要知道为什么会发生这种情况。

enter image description here

1 个答案:

答案 0 :(得分:3)

对于%c,手册页显示(请参阅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.

请注意该部分:前导空白区域的常规跳过被抑制。

另请注意部分:要跳过白色            首先是空格,使用格式的显式空格。

因此,如果您想跳过白色空格,请尝试在%c之前添加空格:

char c;
scanf(" %c", &c);