How to check if a string is a number?

后端 未结 10 2542
没有蜡笔的小新
没有蜡笔的小新 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:31

    #include 
    #include 
    char isNumber(char *text)
    {
        int j;
        j = strlen(text);
        while(j--)
        {
            if(text[j] > 47 && text[j] < 58)
                continue;
    
            return 0;
        }
        return 1;
    }
    int main(){
        char tmp[16];
        scanf("%s", tmp);
    
        if(isNumber(tmp))
            return printf("is a number\n");
    
        return printf("is not a number\n");
    }
    

    You can also check its stringfied value, which could also work with non Ascii

    char isNumber(char *text)
    {
        int j;
        j = strlen(text);
        while(j--)
        {
            if(text[j] >= '0' && text[j] <= '9')
                continue;
    
            return 0;
        }
        return 1;
    }
    

提交回复
热议问题