Ignoring the rest of the line once input has been

2019-06-27 08:56发布

问题:

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?

回答1:

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.



回答2:

If the input length doesn't vary (For example, 6 numbers like your example), you can read your desired input using:

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

then, dispose the rest of the input:

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

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.



回答3:

Previously, do you know how many numbers there are in a line? if your answer is yes, I suggest you try this:

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] );


标签: c input scanf