How to exit a while loop?

#include <stdio.h> main(void) { char ch; while (1) { if ((ch = getchar()) != EOF) { break; } putchar(ch); } return 0; } 

How can I avoid this while ? I tried with EOF but it did not work.

+4
source share
3 answers

I think you mean:

 int ch; 

Because EOF will not fit into char .

also:

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

Your logic is reversed.

+7
source

It:

 char ch; 

incorrectly, EOF does not fit into char . The return type getchar() int , so this code should be:

 int ch; 

Also, as indicated, your logic is reversed. The while ch loop is not EOF , so you can just put it in a while :

 while((ch = getchar()) != EOF) 
+3
source

check the time. It is easier

 while((ch=getchar())!= EOF) { putchar(ch); } 

EOF is used to indicate the end of a file. If you are reading a character from stdin, you can stop this while loop by entering:

  • EOF = CTRL + D (for Linux)
  • EOF = CTRL + Z (for Windows)

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

Example

 while((ch=getchar()) != 0x1b) { // 0x1b is the ascii of ESC putchar(ch); } 
+2
source

All Articles