Ignore the rest of the line after typing in C

This input is as:

6 2 1 2 3 4 5 6 4 3 3 4 5 6 

Where the first number in the first line is the number of variables in the line, the second is the number of lines. How can I get only the first values ​​of n/2 , where n is the number of values ​​in a row and go to the next row?

+4
source share
3 answers

I am surprised that no one mentioned fscanf("%*d") - that the * sign tells fscanf to read the integer value, but ignore it (see the documentation here ). This allows you to 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 characters. If you knew n ahead of time, you could simply write:

 scanf("%d %d %d %*d %*d %*d",&numbers[0],&numbers[1],&numbers[2]); 

You did not ask about it directly, but if you read binary data, there is an additional way to skip the rest of the line. You can read what data you want and then calculate the location of the beginning of the next line (pointer arithmetic is indicated here) and use fseek to go to that location, which can save I / O time. Unfortunately, you cannot do this with ASCII data because numbers do not occupy uniform space.

+3
source

If the input length does not change (for example, 6 numbers, for example, your example), you can read the desired input using:

 scanf("%d %d %d", ...); 

then leave the rest of the input:

 while ((ch = getchar()) != '\n' && ch != EOF); 

If the input length is different , you will have to read it into the buffer. You can then iterate over the string to find the number of spaces in it (So n = spaces + 1), and then repeat again using strtok n / 2 times to get the first n / 2 numbers.

+4
source

Do you know how many digits there are in a line? if your answer is yes, I suggest you try the following:

 int n = numbersInALine(); int i = 0; int *numbers = (int*) malloc( sizeof( int ) * ( n / 2 ) ); for( i = 0; i < n/2; i++ ) scanf( "%d", &numbers[i] ); 
0
source

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


All Articles