user2131316 user2131316 - 1 year ago 57
C Question

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

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 example
1
or
2
as input, but it will be treated as char array for the parameter of argv, but how to make sure the input is a number, in case people typed
hello
or
c
?

Answer Source

Another way of doing it is by using isdigit function. Below is the code for it:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXINPUT 100
int main()
{
    char input[MAXINPUT] = "";
    int length,i; 

    scanf ("%s", input);
    length = strlen (input);
    for (i=0;i<length; i++)
        if (!isdigit(input[i]))
        {
            printf ("Entered input is not a number\n");
            exit(1);
        }
    printf ("Given input is a number\n");
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download