C语言 如何退出while循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13803072/
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
How to exit a while-loop?
提问by kd11
#include <stdio.h>
main(void) {
char ch;
while (1) {
if ((ch = getchar()) != EOF)
{
break;
}
putchar(ch);
}
return 0;
}
How do I escape from this while? I had tried with EOF but it didn't work.
我如何摆脱这种情况while?我曾尝试使用 EOF 但它没有用。
回答by David Schwartz
I think you mean:
我想你的意思是:
int ch;
Because EOFwon't fit in a char.
因为EOF不适合char.
Also:
还:
if ((ch=getchar()) == EOF)
break;
Your logic is backwards.
你的逻辑是反的。
回答by unwind
This:
这个:
char ch;
is wrong, EOFdoesn't fit in a char. The type of getchar()'s return value is intso this code should be:
是错误的,EOF不适合char. getchar()的返回值的类型是int这样的代码应该是:
int ch;
Also, as pointed out, your logic is backwards. It loop while chis not EOF, so you can just put it in the while:
另外,正如所指出的,你的逻辑是倒退的。它循环而ch不是EOF,所以你可以把它放在while:
while((ch = getchar()) != EOF)
回答by MOHAMED
check with the while. It's more simple
查一下。更简单
while((ch=getchar())!= EOF) {
putchar(ch);
}
The EOF is used to indicate the end of a file. If you are reading character from stdin, You can stop this while loop by entering:
EOF 用于指示文件的结尾。如果您正在从 stdin 读取字符,您可以通过输入以下命令来停止此 while 循环:
EOF= CTRL+ D(for Linux)EOF= CTRL+ Z(for Windows)You can make your check also with
Escapechracter or\ncharcter
EOF= CTRL+ D(适用于 Linux)EOF= CTRL+ Z(对于 Windows)您也可以使用
Escape字符或\n字符进行检查
Example
例子
while((ch=getchar()) != 0x1b) { // 0x1b is the ascii of ESC
putchar(ch);
}

