How to check if a string is a number?

后端 未结 10 2514
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 10:03

I want to check if a string is a number with this code. I must check that all the chars in the string are integer, but the while returns always isDigit = 1. I don\'t know wh

相关标签:
10条回答
  • 2020-11-29 10:38

    I need to do the same thing for a project I am currently working on. Here is how I solved things:

    /* Prompt user for input */
    printf("Enter a number: ");
    
    /* Read user input */
    char input[255]; //Of course, you can choose a different input size
    fgets(input, sizeof(input), stdin);
    
    /* Strip trailing newline */
    size_t ln = strlen(input) - 1;
    if( input[ln] == '\n' ) input[ln] = '\0';
    
    /* Ensure that input is a number */
    for( size_t i = 0; i < ln; i++){
        if( !isdigit(input[i]) ){
            fprintf(stderr, "%c is not a number. Try again.\n", input[i]);
            getInput(); //Assuming this is the name of the function you are using
            return;
        }
    }
    
    0 讨论(0)
  • 2020-11-29 10:38

    Your condition says if X is greater than 57 AND smaller than 48. X cannot be both greater than 57 and smaller than 48 at the same time.

    if(tmp[j] > 57 && tmp[j] < 48)
    

    It should be if X is greater than 57 OR smaller than 48:

    if(tmp[j] > 57 || tmp[j] < 48)
    
    0 讨论(0)
  • 2020-11-29 10:53
    if ( strlen(str) == strlen( itoa(atoi(str)) ) ) {
        //its an integer
    }
    

    As atoi converts string to number skipping letters other than digits, if there was no other than digits its string length has to be the same as the original. This solution is better than innumber() if the check is for integer.

    0 讨论(0)
  • 2020-11-29 10:53

    rewrite the whole function as below:

    bool IsValidNumber(char * string)
    {
       for(int i = 0; i < strlen( string ); i ++)
       {
          //ASCII value of 0 = 48, 9 = 57. So if value is outside of numeric range then fail
          //Checking for negative sign "-" could be added: ASCII value 45.
          if (string[i] < 48 || string[i] > 57)
             return FALSE;
       }
    
       return TRUE;
    }
    
    0 讨论(0)
提交回复
热议问题