0

I am working on an algorithm, and I am asked to print "QUIT" when there is no more input to the program.

I am using

char c;
while(c = getchar()){...} 

because I need to look for '\n' characters and numbers.

So I copy the sample input and paste it on my program's to test it, but it keeps waiting for another input and therefore I get a time limit exceeded when I submit it.

PS: I can't use multithreading.

Carlos
  • 121
  • 1
  • 1
  • 8
  • How do you know if there is more input? I might just consider pressing another key if you just wait another second. – Bo Persson Feb 18 '17 at 22:31

3 Answers3

3

You can stop when getchar() returns EOF, like this:

int c;
while ((c = getchar()) != EOF) {...}

Note that c needs to be declared an int, not a char.

To make your program more C++-like, use operator >> instead of getchar in a loop, like this:

char c;
while (cin >> c) {...} 
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

getchar() returns an int, not a char. In particular, it returns EOF on end of file, and EOF is typically -1. So if you store that in a char, it will never compare equal to EOF.

int c;
while ((c = getchar()) != EOF) {
Waxrat
  • 2,075
  • 15
  • 13
0

Are you reading in from a file? If so, getchar() will return EOF: http://www.cplusplus.com/reference/cstdio/getchar/

so

    int c=getchar();
    while (c != EOF) {...}

should work.

  • 1
    You're on the right track, but this code snippet doesn't change the value of `c`. You need to either add `c = getchar();` before the end of the loop body or change the `while` statement to `while ((c = getchar()) != EOF)`. – Pete Becker Feb 18 '17 at 22:48
  • Thanks for that. I just assumed that he would update the variable at the end of the loop, but it's always good to remember that sort of thing. – MJErrelis-Phillips Apr 08 '17 at 00:53