Check if a string has only numbers in C?

前端 未结 5 978
予麋鹿
予麋鹿 2021-01-24 17:57

I\'m trying to write a simple code to check if a string only has numbers in it. So far it\'s not working, any help would be appreciated.

#include          


        
5条回答
  •  孤街浪徒
    2021-01-24 18:35

    You might consider using strspn:

    #include 
    #include 
    
    int main(int argc, char* argv[]) {
        int i;
        for (i=1; i < argc; i++) {
            printf("%s %s\n",
                strlen(argv[i]) == strspn(argv[i], "0123456789") ? "digits" : "mixed",
                argv[i]
            );
        }
    }
    

    Demoed:

    $ ./try foo 123 ba23a 123.4
    mixed foo
    digits 123
    mixed ba23a
    mixed 123.4
    

    strspn returns the initial number of characters from the first argument that appear in the second argument. Super simple examples:

    strspn("abba", "a");  // == 1
    strspn("abba", "b");  // == 0
    strspn("abba", "ab"); // == 2
    

提交回复
热议问题