ProbIem with EOF in C

user196316 picture user196316 · Oct 25, 2009 · Viewed 24.9k times · Source

I'm writing a program which is supposed to read two strings that can contain line breaks and various other characters. Therefore, I'm using EOF (Ctrl-Z or Ctrl-D) to end the string.

This works fine with the first variable, but with the second variable, however, this seems to be problematic as apparently something is stuck in the input buffer and the user doesn't get to type in anything.

I tried to clean the buffer with while (getchar() != '\n'); and several similar variations but nothing seems to help. All cleaning attempts have resulted in an infinite loop, and without cleaning, adding the second variable is impossible.

The characters for both of the variables are read in a loop like this: while((c = getchar()) != EOF), which would suggest it is EOF what I have stuck in my buffer. Or does it affect the behavior of the program in some other way? Is there something wrong with the logic I'm using?

I'm starting to get bit desperate after struggling with this for hours.

code:

#include <stdio.h>
#include <string.h>

int main(void)
{
    int x = 0;
    int c;
    char a[100];
    char b[100];

    printf("Enter a: ");
    while((c = getchar()) != EOF)
    {
        a[x] = c;
        x++;
    }
    a[x] = '\0';
    x = 0;

    /*while (getchar() != '\n'); - the non-working loop*/

    printf("\nEnter b: ");
    while((c = getchar()) != EOF)
    {
        b[x] = c;
        x++;
    }
    b[x] = '\0';

    printf("\n\nResults:\na: %s\n", a);
    printf("b: %s\n", b);

    return(0);
}

Answer

Martin v. L&#246;wis picture Martin v. Löwis · Oct 25, 2009

After you received an EOF from the terminal, you will not receive any additional data. There is no way of un-EOF-ing the input - the end of the file is, well, the end.

So you should define that each variable is input on a separate line, and have users press enter instead of EOF. You still need to check whether you have received eof, because that means that the user actually typed EOF, and you won't see anything else - in this case, you need to break out of the loop and print an error message.