C语言 在 C 中循环读取输入键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7144977/
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
Reading enter key in a loop in C
提问by Gabriel Llamas
How can I read the enter key in a loop multiple times?
如何在循环中多次读取回车键?
I've tried the following with no result.
我试过以下没有结果。
char c;
for (i=0; i<n; i++){
c = getchar ();
fflushstdin ();
if (c == '\n'){
//do something
}
}
And fflushstdin:
和 fflushstdin:
void fflushstdin (){
int c;
while ((c = fgetc (stdin)) != EOF && c != '\n');
}
If I read any other character instead of enter key it works perfect, but with enter key In some iterations I have to press the enter 2 times.
如果我读取任何其他字符而不是 Enter 键,它可以完美运行,但是使用 Enter 键在某些迭代中,我必须按 Enter 2 次。
Thanks.
谢谢。
EDIT: I'm executing the program through putty on windows and the program is running on a virtualized linux mint on virtual box.
编辑:我正在通过 Windows 上的腻子执行程序,并且该程序在虚拟机上的虚拟化 linux mint 上运行。
采纳答案by wormsparty
Why do you call fflushstdin()? If fgetc() returns something different from \n, that character is completely dropped.
为什么要调用 fflushstdin()?如果 fgetc() 返回的内容与 \n 不同,则该字符将被完全删除。
This should work:
这应该有效:
char prev = 0;
while(1)
{
char c = getchar();
if(c == '\n' && prev == c)
{
// double return pressed!
break;
}
prev = c;
}
回答by Vivek
Try
尝试
if (ch == 13) {
//do something
}
ASCII value of enter is 13, sometimes \n won't work.
enter 的 ASCII 值为 13,有时 \n 不起作用。
回答by Petr Abdulin
You should go with:
你应该去:
char c;
for (i=0; i<n; i++){
c = getchar ();
fflushstdin ();
if (c == 13){
//do something
}
}
since 13is ASCII code for Enterkey.
因为13是Enter密钥的ASCII 码。
回答by pmg
You always executing getchartwice (even when there is no need for that). Try limiting calls to fflushstdin:
你总是执行getchar两次(即使没有必要)。尝试将调用限制为fflushstdin:
char c;
for (i=0; i<n; i++){
c = getchar ();
if ((c != EOF) && (c != '\n')) fflushstdin ();
if (c == '\n'){
//do something
}
}

