Check if User Inputs a Letter or Number in C
Solution 1:
It's best to test for decimal numeric digits themselves instead of letters. isdigit.
#include <ctype.h>
if(isdigit(variable))
{
//valid input
}
else
{
//invalid input
}
Solution 2:
#include <ctype.h>
if (isalpha(variable)) { ... }
Solution 3:
isalpha() will test one character at a time. If the user input a number like 23A4, then you want to test every letter. You can use this:
bool isNumber(char *input) {
for (i = 0; input[i] != '\0'; i++)
if (isalpha(input[i]))
return false;
return true;
}
// accept and check
scanf("%s", input); // where input is a pointer to a char with memory allocated
if (isNumber(input)) {
number = atoi(input);
// rest of the code
}
I agree that atoi() is not thread safe and a deprecated function. You can write another simple function in place of that.
Solution 4:
Aside from the isalpha function, you can do it like this:
char vrbl;
if ((vrbl >= 'a' && vrbl <= 'z') || (vrbl >= 'A' && vrbl <= 'Z'))
{
printf("You entered a letter! You must enter a number!");
}
Solution 5:
The strto*()
library functions come in handy here:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE ...
int main(void)
{
char buffer[SIZE];
printf("Gimme an integer value: ");
fflush(stdout);
if (fgets(buffer, sizeof buffer, stdin))
{
long value;
char *check;
/**
* strtol() scans the string and converts it to the equivalent
* integer value. check will point to the first character
* in the buffer that isn't part of a valid integer constant;
* e.g., if you type in "12W", check will point to 'W'.
*
* If check points to something other than whitespace or a 0
* terminator, then the input string is not a valid integer.
*/
value = strtol(buffer, &check, 0);
if (!isspace(*check) && *check != 0)
{
printf("%s is not a valid integer\n", buffer);
}
}
return 0;
}