Check if a string has only numbers in C?

前端 未结 5 986
予麋鹿
予麋鹿 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:34

    You have an error in the for loop - for(i = 0 ; i <= numbers ; ++i)

    numbers is pointer and the comparison of it with integer is forbidden. Correct Code -

    #include 
    #include 
    #include 
    
    int main()
    {
       char numbers[10];
       int i, correctNum = 0;
    
        scanf("%s", numbers);
    
        for(i = 0 ; i < strlen(numbers) ; ++i)
        {
           if(!(numbers[i]>='0' && numbers[i]<='9'))
           {
               correctNum = 1;
                break;
           }
        }
    
        if(correctNum == 1)
        {
             printf("That number has a char in it. FIX IT.\n");
         }
       else
        {
            printf("All numbers. Good.\n");
        }
        return 0;
     }
    

提交回复
热议问题