Using scanf to accept user input

前端 未结 5 649
轻奢々
轻奢々 2020-12-06 13:52

gcc 4.4.2

I was reading an article about scanf. I personally have never checked the return code of a scanf.

#include 

int main(void)
         


        
5条回答
  •  执笔经年
    2020-12-06 14:24

    I don't use scanf() for interactive user input; I read everything as text using fgets(), then parse the input as necessary, using strtol() and strtod() to convert text to numeric values.

    One example of where scanf() falls down is when the user enters a bad numeric value, but the initial part of it is valid, something like the following:

    if (scanf("%d", &num) == 1)
    {
      // process num
    }
    else
    {
      // handle error
    }
    

    If the user types in "12e4", scanf() will successfully convert and assign the "12" to num, leaving "e4" in the input stream to foul up a future read. The entire input should be treated as bogus, but scanf() can't catch that kind of error. OTOH, if I do something like:

    if (fgets(buffer, sizeof buffer, stdin))
    {
      int val;
      char *chk;
      val = (int) strtol(buffer, &chk, 10);
      if (!isspace(*chk) && *chk != 0)
      {
        // non-numeric character in input; reject it completely
      }
      else
      {
        // process val
      }
    }
    

    I can catch the error in the input and reject it before using any part of it. This also does a better job of not leaving garbage in the input stream.

    scanf() is a great tool if you can guarantee your input is always well-formed.

提交回复
热议问题