Check if a string has only numbers in C?

SycoSins picture SycoSins · Jan 21, 2017 · Viewed 12.8k times · Source

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 <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
    char numbers[10];
    int i, correctNum = 0;

    scanf("%s", numbers);

    for(i = 0 ; i <= numbers ; ++i)
    {
        if(isalpha(numbers[i]))
        {
            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;
}

Answer

RoadRunner picture RoadRunner · Jan 21, 2017

Adding to the others answers, you can also use strtol to determine if a string has all numbers or not. It basically converts the string to an integer, and leaves out any non-integers. You can read the man page for more information on this function, and the extensive error checking you can do with it.

Also, you should use:

scanf("%9s", numbers);

Instead of:

scanf("%s", numbers);

To avoid buffer overflow.

Here is some example code:

#include <stdio.h>
#include <stdlib.h>

#define MAXNUM 10
#define BASE 10

int main(void) {
    char numbers[MAXNUM];
    char *endptr;
    int number;

    printf("Enter string: ");
    scanf("%9s", numbers);

    number = strtol(numbers, &endptr, BASE);

    if (*endptr != '\0' || endptr == numbers) {
        printf("'%s' contains non-numbers\n", numbers);
    } else {
        printf("'%s' gives %d, which has all numbers\n", numbers, number);
    }

    return 0;
}

Example input 1:

Enter string: 1234

Output:

'1234' gives 1234, which has all numbers

Example input 2:

Enter string: 1234hello

Output:

'1234hello' contains non-numbers