Check if input is float else stop

前端 未结 6 552
[愿得一人]
[愿得一人] 2020-12-21 22:06
scanf(\"%f\", &num);

I have to check if thats a valid float variable and stop executing if it has symbols like @ or !

6条回答
  •  清歌不尽
    2020-12-21 22:44

    Read your input as text, then convert it with the strtod library function; that allows you to check if the input contains any invalid characters:

    #include 
    #include 
    #include 
    ...
    char buf=[81];
    double result = 0.0;
    ...
    if ( fgets( buf, sizeof buf, stdin ) != NULL )
    {
      char *chk;
      double tmp = strtod( buf, &chk );
      if ( isspace( *chk ) || *chk == 0 )
        result = tmp;
      else
        fprintf( stderr, "%s is not a valid floating-point number\n", buf );
    }
    

    After the call to strtod, the variable chk will point to the first character in the string that is not part of a valid floating-point constant. If this character is whitespace or 0, then you're good; otherwise you have bad input.

    The advantage to this method over scanf is that if your input starts with just one valid character (such as "1blkjhsdf"), it will convert and assign the "1" and return a 1, indicating a successful conversion, even though you'd probably want to reject that input. It also consumes the entire input string (provided the input buffer is large enough), so it doesn't leave any garbage in the input stream to foul up the next read.

    scanf is a good tool to use when you know your input is well-formed; otherwise, better to use the method above.

提交回复
热议问题