How to exit a while-loop?

≡放荡痞女 提交于 2019-12-07 08:22:26

问题


#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.


回答1:


I think you mean:

int ch;

Because EOF won't fit in a char.

Also:

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

Your logic is backwards.




回答2:


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)



回答3:


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);
}


来源:https://stackoverflow.com/questions/13803072/how-to-exit-a-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!