Check if input is float else stop

前端 未结 6 544
[愿得一人]
[愿得一人] 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:53

    You can check the return value from scanf(). If you look at this page :

    Return value

    On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

    So something like :

    if ( scanf( "%f", &num ) <= 0 )
    {
        // Stop the execution
    }
    // Continue
    

    will do what you want.

提交回复
热议问题