Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how use EOF stdin in C

Tags:

c

stdin

feof

scanf

I need to input coordinates into an array until EOF is encountered, but something is wrong in my code. I used ctrl+Z, ctrl+D

int main()
{
    int x[1000],y[1000];
    int n=0,nr=0,a,b,i;
    printf("Enter the coordinates:\n");
    while(scanf ( "%d %d ", &a, &b) == 2)
    {
     x[n]=a;
     y[n]=b;
     n++;
    }
    if (!feof(stdin))
    {
       printf("Wrong\n");
    }
    else
    {
       for(i=0;i<n;i++)
       printf("%d %d\n", x[i], y[i]);
    }

  return 0;
}
like image 468
Trung Nguyen Avatar asked Nov 11 '11 13:11

Trung Nguyen


1 Answers

I suggest using

while(!feof(stdin) && scanf ( "%d %d ", &a, &b) == 2)

and actually it is better to test feof after (not before!) some input operation, so:

while (scanf("%d %d ", &a, &b) == 2 && !feof(stdin))

BTW, on many systems stdin is line buffered, at least with interactive terminals (but perhaps not when stdin is a pipe(7)), see setvbuf(3)

On Linux & POSIX you might consider reading every line with getline(3) (or even with readline(3) if reading from the terminal, since readline offers editing abilities), then parsing that line with e.g. sscanf(3) (perhaps also using %n) or strtol(3)

like image 99
Basile Starynkevitch Avatar answered Oct 05 '22 15:10

Basile Starynkevitch