How to check if a string is a number?

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

    More obvious and simple, thread safe example:

    #include 
    #include 
    #include 
    
    int main(int argc, char **argv)
    {
        if (argc < 2){
            printf ("Dont' forget to pass arguments!\n");
            return(-1);
        }
    
        printf ("You have executed the program : %s\n", argv[0]);
    
        for(int i = 1; i < argc; i++){
            if(strcmp(argv[i],"--some_definite_parameter") == 0){
                printf("You have passed some definite parameter as an argument. And it is \"%s\".\n",argv[i]);
            }
            else if(strspn(argv[i], "0123456789") == strlen(argv[i])) {
                size_t big_digit = 0;
                sscanf(argv[i], "%zu%*c",&big_digit);
                printf("Your %d'nd argument contains only digits, and it is a number \"%zu\".\n",i,big_digit);
            }
            else if(strspn(argv[i], "0123456789abcdefghijklmnopqrstuvwxyz./") == strlen(argv[i]))
            {
                printf("%s - this string might contain digits, small letters and path symbols. It could be used for passing a file name or a path, for example.\n",argv[i]);
            }
            else if(strspn(argv[i], "ABCDEFGHIJKLMNOPQRSTUVWXYZ") == strlen(argv[i]))
            {
                printf("The string \"%s\" contains only capital letters.\n",argv[i]);
            }
        }
    }
    

提交回复
热议问题