C语言 在 c 上使用 getchar() 在输入后获取“Enter”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3969871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using getchar() on c gets the 'Enter' after input
提问by SnapDragon
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.
我正在尝试编写一个简单的程序,要求用户从循环菜单中进行选择。我使用 getchar() 来获取输入,但是我注意到当我输入一个字符并按“Enter”时,程序会进行两个循环(就像我按了两次一样),一个是字符作为输入,另一个是“Enter”作为输入。
How do I fix this?
我该如何解决?
回答by Michael Goldshteyn
You need to read about canonical vs. non-canonical input. The following Stack Overflow question addresses this:
您需要阅读规范与非规范输入。以下堆栈溢出问题解决了这个问题:
回答by KeatsPeeks
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 (\nin your example). You need to clear the input buffer before calling getchar()again:
getchar()返回输入缓冲区中的第一个字符,并将其从输入缓冲区中删除。但是其他字符仍在输入缓冲区中(\n在您的示例中)。您需要在getchar()再次调用之前清除输入缓冲区:
void clearInputBuffer() // works only if the input buffer is not empty
{
do
{
c = getchar();
} while (c != '\n' && c != EOF);
}
回答by Prasoon Saurav
Add a getchar()after the getchar():P
getchar()在getchar():P后面加一个
回答by JaredPar
The easiest way is to filter out the enter key as the return value from getchar
最简单的方法是过滤掉作为返回值的回车键 getchar
char c = (char)getchar();
if ( c != '\n' ) {
...
}
回答by Ohad Schneider
How about
怎么样
#include <stdio.h>
/*! getline() reads one line from standard input and copies it to line array
* (but no more than max chars).
* It does not place the terminating \n in line array.
* Returns line length, or 0 for empty line, or EOF for end-of-file.
*/
int getline(char line[], int max)
{
int nch = 0;
int c;
max = max - 1; /* leave room for 'printf("Pick an option: ");
fflush(stdout);
scanf("%d", &option);
switch(option)
{
case 0 : do_something(); break;
case 1 : do_something_else(); break;
...
default: bad_option(); break;
}
' */
while ((c = getchar()) != EOF) {
if (c == '\n')
break;
if (nch < max) {
line[nch] = c;
nch = nch + 1;
}
}
if (c == EOF && nch == 0)
return EOF;
line[nch] = '/**
* Prints a prompt to stdout and reads an input response, writing
* the input value to option.
*
* @param prompt [in] - prompt written to stdout
* @param option [out] - option entered by user
*
* @return - 1 on success, 0 on failure. If return value is 0, then option
* is not changed.
*/
int getOption(const char *prompt, char *option)
{
char input[3]; // option char + newline + 0 terminator
int result = 0;
printf("%s: ", prompt);
fflush(stdout);
if (fgets(input, sizeof input, stdin))
{
/**
* Search for a newline character in the input buffer; if it's not
* present, then the user entered more characters than the input buffer
* can store. Reject the input, and continue to read from stdin until
* we see a newline character; that way we don't leave junk in the
* input stream to mess up a future read.
*/
char *newline = strchr(input, '\n');
if (!newline)
{
printf("Input string is too long and will be rejected\n");
/**
* Continue reading from stdin until we find the newline
* character
*/
while (!newline && fgets(input, sizeof input, stdin))
newline = strchr(input, '\n');
}
else
{
*option = input[0];
result = 1;
}
}
else
printf("Received error or EOF on read\n");
return result;
}
';
return nch;
}
回答by John Bode
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:
有几种选择。如果您的菜单选项已编号,您可以使用scanf()读取一个整数值并根据该值进行切换:
The advantage of this option is that the %dconversion specifier skips over any leading whitespace, including newline characters, so you don't have to worry about any unread \nclogging up the input stream (in fact, most of the conversion specifiers skip leading whitespace; %cdoesn't, making it behave a lot like getchar()).
此选项的优点是%d转换说明符跳过任何前导空格,包括换行符,因此您不必担心任何未读\n阻塞输入流(实际上,大多数转换说明符跳过前导空格;%c不会't,使它的行为很像getchar())。
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 %dconversion specifier, and will stay stuck in the input stream until a call to getchar()or scanf()with a %sor %cconversion specifier.
此选项的缺点是,如果有人对输入中的非数字字符进行粗指,则不会使用%d转换说明符读取该字符,并且将停留在输入流中,直到使用或转换说明符调用getchar()or之前. scanf()%s%c
A better option is to read all input as character stringsusing fgets(), then parse and validate as necessary.
更好的选择是阅读所有输入的字符字符串使用fgets(),然后解析和验证是必要的。
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.
是的,在一个愚蠢的菜单选项中阅读大量工作,这就是简单的版本。欢迎来到 C 交互输入处理的奇妙世界。

