How to use EOF stdin in C

I need to enter the 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; } 
+4
source share
2 answers

I suggest using

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

and actually it's better to check feof after (not earlier!) some input operation, therefore:

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

BTW, many stdin systems support line buffering, at least via interactive terminals (but maybe not when stdin is pipe (7) ), see setvbuf (3)

On Linux and POSIX, you can look at each line using getline (3) (or even readline (3) when reading from the terminal, because readline offers editing options), then parse this line, for example sscanf (3) (possibly also using %n ) or strtol (3)

+14
source

The only real problem that I see in your code is the extra spaces in the scanf format string. These spaces tell scanf use a space character in the input, which makes scanf not return to your code until it reaches the character without spaces (e.g. letter, number, punctuation or EOF).

As a result, after you enter two numbers and then Enter , you must type Ctrl - D ( Ctrl - Z on DOS / Windows) twice before your program escapes the while loop.

+3
source

Source: https://habr.com/ru/post/1380767/


All Articles