Ignoring the rest of the line once input has been gotten in C
An answer to this question on Stack Overflow.
Question
Given input like:
6 2
1 2 3 4 5 6
4 3 3 4 5 6
Where first number in
first line is number of variables in line, second one is number of lines.
How it is possible to get only first n/2 values, where n is number of values in a line and skip to the next line?
Answer
I'm surprised no one mentioned fscanf("%*d") - that * sign tells fscanf to read an integer value, but to ignore it (see the documentation here). This lets you do something like:
int numbers[MAX_NUMS];
int n = numbers_in_line();
for( i = 0; i < n; i++ )
if(i<n/2)
fscanf("%d", &numbers[i]);
else
fscanf("%*d");
which seems clearer than just reading in the rest of the chars. If you knew n ahead of time, you could also just write:
scanf("%d %d %d %*d %*d %*d",&numbers[0],&numbers[1],&numbers[2]);
You didn't ask about this directly, but if you were reading binary data, there is an additional way to skip the rest of the line. You could read what data you want, then calculate the location of the beginning of the next line (some pointer arithmetic here) and use the fseek function to jump ahead to that location, which could save some I/O time. Unfortunately, you can't do this with ASCII data because the numbers do not take up uniform amounts of space.