what happens when you input things like 12ab to scanf(“%d”,&argu)?

前端 未结 5 1941
无人共我
无人共我 2020-12-11 07:08

I came across this problem when I want to check what I input is number. The scanf function will return 1 if I successfully input a number. So here is what I wro

5条回答
  •  没有蜡笔的小新
    2020-12-11 07:47

    But when I input things like abcd to it, the loop would go forever and not stop for prompt.

    That's because if scanf encounters a character that does not match the conversion specifier, it leaves it in the input stream. Basically, what's happening is that scanf reads the character a from the input stream, determines that it's not a valid match for the %d conversion specifier, and then pushes it back onto the input stream. The next time through the loop it does the same thing. And again. And again. And again.

    fflush is not a good solution, because it isn't defined to work on input streams.

    For the input "12ab", scanf will read and convert "12", leaving "ab" in the input stream.

    The best solution is to read all your input as text, then convert to numeric types using strtol (for integral values) and strtod (for real values). For example:

    char input[SIZE]; // assume SIZE is big enough for whatever input we get
    int value;
    
    if (fgets(input, sizeof input, stdin) != NULL)
    {
      char *chk;
      int tmp = (int) strtol(input, &chk, 10);
      if (isspace(*chk) || *chk == 0)
        value = tmp;
      else
        printf("%s is not a valid integer string\n", input);
    }
    

    chk points to the first character in the input stream that isn't a decimal digit. If this character is not whitespace or the 0 terminator, then the input string wasn't a valid integer. This will detect and reject inputs like "12ab" as well as "abcd".

    scanf is a good solution if you know your input is always going to be properly formed and well-behaved. If there's a chance that your input isn't well-behaved, use fgets and convert as needed.

提交回复
热议问题