scanf正在读取换行符 [英] scanf is reading new line character

查看:174
本文介绍了scanf正在读取换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

gets也有同样的问题.许多帖子建议使用fgets()而不是同时使用上述两种,但是我需要知道为什么会发生这种情况.

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.

推荐答案

对于%c,手册页上说(请参阅

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.

请注意部分:通常的前导空白跳格被抑制.

还请注意部分:要跳过白色 空格,请使用以下格式的显式空格.

Also Notice the part: To skip white space first, use an explicit space in the format.

因此,如果要跳过空格,请尝试在%c之前添加一个空格:

So if you want to skip whites spaces, try adding a space before %c:

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

这篇关于scanf正在读取换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆