在 c 上使用 getchar() 会得到“Enter”;输入后
我正在尝试编写一个简单的程序,要求用户从循环的菜单中进行选择。 我使用 getchar() 来获取输入,但是我注意到,当我输入一个字符并按“Enter”键时,程序会进行两个循环(就像我按两次一样),一个将字符作为输入,另一个用于“Enter”作为输入。
我该如何解决这个问题?
I'm trying to write a simple program that asks a user to choose from a menu in a loop.
I use getchar() to get the input, however i've noticed that when I enter a char and press 'Enter' the program makes two loops (as if i pressed twice) one the char as an input and another for 'Enter' as an input.
How do I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
getchar()
返回输入缓冲区中的第一个字符,并将其从输入缓冲区中删除。但其他字符仍在输入缓冲区中(示例中为\n
)。您需要在再次调用getchar()
之前清除输入缓冲区:getchar()
returns the first character in the input buffer, and removes it from the input buffer. But other characters are still in the input buffer (\n
in your example). You need to clear the input buffer before callinggetchar()
again:在
getchar()
之后添加getchar()
:PAdd a
getchar()
after thegetchar()
:P最简单的方法是过滤掉 Enter 键作为
getchar
的返回值The easiest way is to filter out the enter key as the return value from
getchar
怎么样
来源
How about
Source
你已经回答了你自己的问题;你必须以某种方式处理换行符。
有几种选择。如果您的菜单选项是编号的,您可以使用
scanf()
读取整数值并根据该值进行切换:此选项的优点是
%d
转换说明符会跳过任何前导空格,包括换行符,因此您不必担心任何未读的\n
堵塞输入流(事实上,大多数转换说明符会跳过前导空格;%c
不会,这使得它的行为很像getchar()
)。此选项的缺点是,如果有人在输入中误操作了非数字字符,则不会使用
%d
转换说明符读取该字符,并且将停留在输入流中,直到使用%s
或%c
转换说明符调用getchar()
或scanf()
。更好的选择是使用
fgets()
将所有输入读取为字符字符串,然后根据需要进行解析和验证。是的,在一个愚蠢的菜单选项中阅读需要做很多工作,而这就是简单的版本。欢迎来到 C 语言交互式输入处理的奇妙世界。
You've kind of answered your own question; you have to deal with the newline character somehow.
There are several options. If your menu options are numbered, you can use
scanf()
to read in an integer value and switch based on that:The advantage of this option is that the
%d
conversion specifier skips over any leading whitespace, including newline characters, so you don't have to worry about any unread\n
clogging up the input stream (in fact, most of the conversion specifiers skip leading whitespace;%c
doesn't, making it behave a lot likegetchar()
).The disadvantage of this option is that if someone fat-fingers a non-digit character in their input, it won't be read with the
%d
conversion specifier, and will stay stuck in the input stream until a call togetchar()
orscanf()
with a%s
or%c
conversion specifier.A better option is to read all input as character strings using
fgets()
, then parse and validate as necessary.Yes, that's a lot of work to read in one stupid menu option, and that's the simple version. Welcome to the wonderful world of interactive input processing in C.