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:
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: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
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'.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; }
Anyone has a different idea?



LinkBack URL
About LinkBacks


