Check if input is float else stop

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

    You cannot check for both of your conditions in scanf. I would suggest reading whole input into a string, look for special characters. Once this test passes, try re-processing it into a string via sscanf. To search for special characters there is a strpbrk defined in string.h

    char* specials = "%@!";
    char* buffer[SOME_SIZE];
    double value;
    int err;
    
    scanf("%s", buffer);
    if( strpbrk(buffer, specials) ) return SPECIAL_FOUND;
    err = sscanf(buffer, "%f", &value);
    if(err <= 0) return NOT_VALID_INPUT; //NOTE: there should probably be not EOF case
    
    // process your value
    

    Note: I did not check the code it's a rough idea to play with.

提交回复
热议问题