how to check if the input is a number or not in C?

前端 未结 8 2092
暖寄归人
暖寄归人 2020-11-27 05:38

In the main function of C:

void main(int argc, char **argv)
{
   // do something here
}

In the command line, we will type any number for ex

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 05:55

    I was struggling with this for awhile, so I thought I'd just add my two cents:

    1) Create a separate function to check if an fgets input consists entirely of numbers:

    int integerCheck(){
    char myInput[4];
    fgets(myInput, sizeof(myInput), stdin);
        int counter = 0;
        int i;
        for (i=0; myInput[i]!= '\0'; i++){
            if (isalpha(myInput[i]) != 0){
                counter++;
                if(counter > 0){
                    printf("Input error: Please try again. \n ");
                    return main();
                }
            }
    
        }
        return atoi(myInput); 
    }
    

    The above starts a loop through every unit of an fgets input until the ending NULL value. If it comes across a letter or an operator, it adds "1" to the int "counter" which is initially set to 0. Once the counter becomes greater than 0, the nested if statement instructs the loop to print an error message & then restart the program. When the loops completes, if int 'counter' is still the value of 0, it returns the initially inputted integer to be used in the main function ...

    2) the main function would be:

    int main(void){
    unsigned int numberOne;
    unsigned int numberTwo;
    numberOne = integerCheck();
    numberTwo = integerCheck();
    return numberOne*numberTwo;
    
    }
    

    Assuming both integers are inputted correctly, the example provided will yield the result of int "numberOne" multiplied by int "numberTwo". The program will repeat for however long it takes to get two properly inputted integers.

提交回复
热议问题