开发者

Question about scanf function in C

I've got a question about how the scanf function works. In this program:

#include <stdio.h>

int main(void) {

    int x;
    char y;

    printf("Write a number: ");
    scanf("%d", &x);

    printf("Write a character: ");
    scanf(" %c", &y);

    printf("%d", x);
    printf("%c", y);

    return 0;
}

If the user writes a number then hit enter then the scanf function would see from the format string that is should expect a number. When the user taps enter it would not read the new-line character and put it back in the buffer. Then since I am reading a character next I need to have a whitespace in the format string because the scanf function would otherwise take the new-line character and put in the y-variable.

However I am just curious about what happened if the user wrote something like

j344lk4fjk388

Would it put everything back in the buffer? And everything that gets "put-back" in the buffer would it automatically be r开发者_如何学Pythonead by the next scanf function in my program?

I'm reading: C Programming A Modern Approach 2nd Edition


You should always check the return value from scanf() to ensure that all the conversions you expected were successful.

Given the sample input:

j344lk4fjk388

The first scanf() would fail because j cannot be converted to an integer - returning 0 for the number of successful conversions. The second call would succeed, returning 'j' as the character.

If you need the string to be treated as an integer, use fgets() or a relative (perhaps POSIX getline()) to read the string, then strtoul() (or the appropriate relative - strtol(), strtoll(), strtoull(), strtoimax() or strtoumax()), specifying a base of at least 21 to convert the 'j', or 23 to take the 'l' and 'k'.


Error handling

scanf is usually used in situations when the program cannot guarantee that the input is in the expected format. Therefore a robust program must check whether the scanf call succeeded and take appropriate action. If the input was not in the correct format, the erroneous data will still be on the input stream and must be read and discarded before new input can be read. An alternative method of reading input, which avoids this, is to use fgets and then examine the string read in. The last step can be done by sscanf, for example.

http://en.wikipedia.org/wiki/Scanf


It will put everything that was not matched by scanf back in the buffer. Eg: scanf("%i %i",...) given the input "12 qwe" will leave qwe in the buffer but not 12. (The spec suggests it won't put the space back, and a quick test confirms.) That said, the documentation is rather unclear, and it is probably a bad idea to rely on it without doing plenty of tests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜