繁体   English   中英

scanf正在读取换行符

[英]scanf is reading new line character

scanf()始终丢弃空格和换行符。 但是当我给一个字符并按Enter时,将读取并存储换行符。 因此,我无法读取所需的字符数。 我的代码是否有问题,或者其他问题?

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

在此处输入图片说明

对于%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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM