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;
}
You might consider using
strspn
:Demoed:
strspn
returns the initial number of characters from the first argument that appear in the second argument. Super simple examples: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 -
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:
Instead of:
To avoid buffer overflow.
Here is some example code:
Example input 1:
Output:
Example input 2:
Output:
Run the loop from
0
to1
less than thelength
of the input.