I have a C program where the user will be entering integers or doubles into the command line as input. Negative numbers are allowed, but I have the issue of when a user enters some thing like this:
1-1
It just gets parsed as being a one. I created a function to test whether or not the user input is a valid number, but I’m not sure how to catch instances like that, or the same goes for input like 1+1, 1)2, so on.
Here is the function I created:
int check_number(char *userInput) {
int i;
//check each character
for (i = 0; userInput[i] != '\0'; i++){
if (isalpha(userInput[i])){
printf("Invalid input.\n");
return -1;
}
}
return 0;
}
What should I do to not allow any other random characters (besides letters, since those are already getting tested with isalpha) in the middle of user input?
Basically you want the first character to be either a minus or a digit (and maybe a period) all subsequent characters should be digits or a period. But you will probably also want to count the periods to make sure there is only one. If you want to accept scientific notation as well you will need to deal with that as well.
Checking for not isalpha is the wrong way around, you should check for the characters that are allowed.
Basically something like: