# Problems Reading Line With Unknown Number of Integers

• 09-27-2011
envec83
Problems Reading Line With Unknown Number of Integers
I need to read a file via stdin (so I'll run my program as ./program <input.txt> output.txt) but I am having problems doing so correctly. The input file starts with an integer x, and x lines follow. Each line starts with an s (for sub-set), followed by an unkown number of integers. So something like this:

Code:

```5 s 1 2 5 s 3 7 9 11 13 s 2 4 8 10 12 s 3 s 1 5 8 10 13 15 17```
The problem I am facing is to know when to stop, given that each line has an unknown number of integers. I tried this code:

Code:

```int main(){         int i,x,n;         char c;         scanf("%d",&x);         scanf("%c",&c); /*to remove the first line break*/         for (i=0;i<x;i++){                 scanf("%c",&c); /*process the 's'*/                 while(scanf("%d",&n);){ /*repeat while scanf matches a number*/                                                printf("%d\n",n);                 }                        }                return 0; }```
But it goes into an infinite loop. Somehow the scanf keeps reading the last number of the first line over and over again. I also tried to read the whole line at once, but then I don't know how to separate the numbers from the 's'.

Anyone has a different idea?
• 09-27-2011
laserlight
Is there a known maximum number of integers per line? Also, are you not going to read this into an array? If you are going to read integer by integer, then the number of them really does not matter as you just need to process one at a time, until there are none left.
• 09-27-2011
MK27
Perhaps scanf() is returning EOF at the end of the line for some reason, which is a non-zero value. Try:

Code:

`while(scanf("%d",&n) == 1)`
• 09-27-2011
envec83
That fixed it.

Thanks a lot.