Reputation: 21
Hi I need to prompt a user for some input and then validate it. The input must only be validated if it is a positive integer and not greater then 23. The only problem I am having with this is when the user enters a non-numerical input like "hello." The code below does not successfully detect that any input is non-numerical and though I have tried many methods to do this, none of them seem to work. Below is the closest I seem to have gotten by taking the input as a string then converting it to an integer, however it still does not work. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void) {
int height;
char input[50];
int cont = 0;
while (cont == 0) {
printf("Please provide a non-negative integer no greater than 23.\n");
scanf("%s", &input);
height = atoi(input);
if (height <= 23 && height >= 0) {
cont = 1;
} else {
//do nothing
}
}
printf("Valid Input.\n");
return 0;
}
Upvotes: 1
Views: 134
Reputation: 775
I am assuming that you have to consider the whole input into the consideration rather than only certain parts like "12jjj" and "23h" as invalid.
In my opinion, since 23 is only 2 char, so there is no harm in checking the length of the string and the individual characters.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
bool ValidateInput (char * input, int &output)
{
if (strlen(input) > 2)
return false;
for (int index = 0; index < strlen (input); index++)
{
if ((input[index] < '0') || input[index] > '9')
return false;
}
output = atoi(input);
return true;
}
int main(void) {
int height;
char input[50];
int cont = 0;
while (cont == 0) {
printf("Please provide a non-negative integer no greater than 23.\n");
scanf("%s", input);
if (ValidateInput (input, height))
break;
}
printf("Valid Input.\n");
return 0;
}
I hope this helps.
Upvotes: 0
Reputation: 40145
#include <stdio.h>
int main(void) {
int height;
while(1){
printf("Please provide a non-negative integer no greater than 23.\n");
//if(2==scanf("%d%c", &height, &nl) && nl == '\n' && 0<= height && height <= 23)//more limited for "number\n"
if(1==scanf("%d", &height) && 0<= height && height <= 23)
break;
//Clear of invalid input
while(getchar()!='\n')
;
}
printf("Valid Input(%d).\n", height);
return 0;
}
Upvotes: 0
Reputation: 992747
The atoi()
function has no provision for returning an error indicator. Instead, you can use the strtol()
function:
char *end;
height = strtol(input, &end, 10);
if (end == input) {
// no digits were entered
puts("Invalid input.");
continue;
}
Upvotes: 4