سؤال

I have 5 lines of input and I only care about using two of them (they're in a text file):

1 -- input function one
L 123.0 21.0
2 -- input function 2
2.0 3.0
3.0 2.0

I want to use 1 from the first line, and then I want to skip to line 2.

After I've used line 2 I want to read the number 2 in line 3.

Again I want to skip to the end of the line and use lines four and five.

I'm only able to use getchar(), scanf, if and while to do this. Here is a portion of my code, I'm just trying to get it working.

int
main(int argc, char *argv[]) {
    char ch;
    int j;
    if(scanf("%d", &j) == 1){
        printf("Got %d lines\n", j);
    }
    scanf("%c", &ch);
    printf("%c", ch);
    return 0;
}

If I put

scanf("%d -- input function one\n", &j)

Then I end up where I want to be, but ONLY for the case where "-- 'stuff' " is the exact phrase after the %d in scanf.

Is there anything I can do to skip to the end of the line? to get output:

Got 1 lines

L

هل كانت مفيدة؟

المحلول

Here's my suggestion.

// Read 1 from the first line.
if(scanf("%d", &j) == 1){
    printf("Got %d lines\n", j);
}

// Read the rest of the line but don't
// save it. This is the end of the first line
scanf("%*[^\n]s");

// Read the next line but don't save it.
// This is the end of the second line.
scanf("%*[^\n]s");

// Now read the 2 from the third line.
if(scanf("%d", &j) == 1){
    printf("Got %d lines\n", j);
}

// Read the rest of the line but don't
// save it. This is the end of line 3
scanf("%*[^\n]s");

// Now the fourth line can be read.

Update

The lines

scanf("%*[^\n]s");

should be

scanf("%*[^\n]s\n");

in order to consume the '\n' as well.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top