read the data and skip parenthese with scanf

2019-02-25 23:08发布

问题:

I write a C program to pick the data from the the std input, which starts with a number indicating the number of the data sets, then there are N pairs of data, in the form: (x y), so I write the code as below:

#include <stdio.h>

int main()
{
    int n_sets;
    scanf("%d", &n_sets);
    int i;
    for(i = 0; i < n_sets; ++i)
    {
        int m, n;
        scanf("(%d %d)", &m, &n);
        printf("%d\t%d\n", m, n);
    }

    return 0;
}

but it doesn't work. After I input the number of the data set, the program print the uninitialized m&n directly. But when I add a space before the (%d %d), it works fine. Somebody can explain this?

回答1:

When you have character literals in your argument to scanf(), it expects to find those literals exactly as specified in the format string.

scanf("%d", &n_sets);

correctly reads n_sets, and stops at the newline or other whitespace character in the buffer. The next scanf() :

scanf("(%d %d)", &m, &n);

expects to find an open parenthesis at the beginning of the input, but finds a whitespace character instead. So it fails, and scanf() returns without having read anything. Consequently, your m and n remain uninitialized, and garbage results.

When you put in the space before the open parenthesis like so:

scanf(" (%d %d)", &m, &n);

it tells scanf() to skip any leading whitespace before the parenthesis in the input buffer, so the program works correctly.



回答2:

change

scanf("%d", &n_sets);

to

scanf("%d\n", &n_sets);

and input your n_sets ending up with a [enter], it works.



回答3:

Assuming your input is like this:

2 (1 2) (3 4)

There is a space(or new line?) after the first number, so change the scanf in the loop to:

scanf("\n(%d %d)", &m, &n);
//     ^^


回答4:

It sounds like the input into the program has some amount of whitespace before the value you want scanf to parse. The space in the string tells scanf to ignore whitespace. Without it, scanf is looking for an exact match immediately.



标签: c scanf