Check if input is float else stop

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

    scanf is not your friend, here. Even if you check the result to ensure that you read one whole argument successfully, that doesn't really guarantee that the input is valid in a meaningful sense.

    Given input like:

    1!!!1!oneone!
    

    the %f parsing will stop (but succeed) after reading the first 1, and leave the read pointer at the following !. This may not be what you consider "valid input".

    In that case, try:

    if (scanf("%f%c", &f, &c) == 2 && isspace(c))
        /* success */
    

    This will, however, accept things like:

    1 oneoneonespace!bang
    

    If anything on the same line is to be considered garbage, then it gets difficult, because scanf doesn't distinguish between spaces and newlines. Perhaps try something like this:

    char buffer[1024];
    if (fgets(buffer, sizeof(buffer), stdin) != NULL)
    {
        if (sscanf(buffer, "%f %c", &f, &c) == 1)
            /* success */
    }
    

提交回复
热议问题