How to validate input using scanf

前端 未结 6 1826
死守一世寂寞
死守一世寂寞 2020-11-29 11:55

How can I validate the user input by using scanf. Right now I have something like this, but doesn\'t work.

NOTE: I have the atoi just to validate that the scanf vali

6条回答
  •  庸人自扰
    2020-11-29 12:14

    What you specified in the first argument to scanf are conversion specifiers. scanf will try to convert the input to the format but sometimes you might be surprised what it will match against :)

    The first check you should do is on the return value from scanf (it will give you the number of matching inputs). If you don't get the number you are expecting then you know that something is wrong with the input. In your case it should be 1.

    if( scanf("%[0987654321.-]s", buf) == 1 )
    {
          if( sanit_check( buf ) ) 
          {
          /* good input */
          }
          else
          {
          /* invalid input */
          }
    }
    else 
    {
    /* invalid input */
    }
    

    Beyond that you will need to do you own sanity checks on the conversion that you asked scanf to do.

提交回复
热议问题