4
votes

I'm trying to match lines with a format like "point %d %d". So I only need to two those two integers, then the "point" is hard-coded in the format string. As I understand reading Linux man pages of scanf, this should work correctly.

The next code, the way I want to use, the first call to scanf works, but the next calls scanf return with an error code and never take more numbers from the stdin (scanf doesn't block waiting for more input from stdin):

for (;;)
{
    scanf("point %d %d", &x, &y);
    printf("=> point %d %d\n", x, y);
}

In this way, everything work as expected:

    int x, y;
    char s[10];

    for (;;)
    {
        scanf("%s %d %d", s, &x, &y);
        printf("=> point %d %d\n", x, y);
    }

Any suggestion about what could I am misunderstanding?

Thanks.

3

3 Answers

3
votes

There's still unconsumed data such as end-of-line characters in stdin that make the upcoming scans to stop with a non-match. In the second version this end-of-line data gets consumed by the %s.

I suggest you fgets to a buffer first and then sscanf it. And do check your return values.

1
votes

My guess is that you are not giving it proper input. For example this input will not work:

4 5

This should work:

point 4 5

You didn't mention the error code, but it is probably saying that you didn't follow the format correctly (i.e. put in point before the numbers).

0
votes

As a good programming practice you should flush the standard input before taking inputs from user.