How to exit a while-loop?

扶醉桌前 提交于 2019-12-05 17:58:55

I think you mean:

int ch;

Because EOF won't fit in a char.

Also:

if ((ch=getchar()) == EOF)
       break;

Your logic is backwards.

This:

char ch;

is wrong, EOF doesn't fit in a char. The type of getchar()'s return value is int so this code should be:

int ch;

Also, as pointed out, your logic is backwards. It loop while ch is not EOF, so you can just put it in the while:

while((ch = getchar()) != EOF)

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 = CTRL + D (for Linux)
  • EOF = CTRL + Z (for Windows)

    You can make your check also with Escape chracter or \n charcter

Example

while((ch=getchar()) != 0x1b) { // 0x1b is the ascii of ESC
     putchar(ch);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!