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?
I'm surprised no one mentioned
fscanf("%*d")
- that*
sign tellsfscanf
to read an integer value, but to ignore it (see the documentation here). This lets you do something like:which seems clearer than just reading in the rest of the chars. If you knew
n
ahead of time, you could also just write: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.If the input length doesn't vary (For example, 6 numbers like your example), you can read your desired input using:
then, dispose the rest of the input:
If the input length does vary, you'll have to read it into a buffer. Then you can iterate over the string to find the number of spaces in it (So n = spaces + 1), then iterate again using
strtok
n/2 times to get the first n/2 numbers.Previously, do you know how many numbers there are in a line? if your answer is yes, I suggest you try this: