-
Validating an Integer
Dear all,
I am a total beginner to C - I've got some code that I'm trying to write that ensures you're entering an integer between 1 and 1000 inclusive. I want to verify the integer is the correct length (4), and that it is an integer.
Code:
void enterN(int *inputInteger)
{
char str[5] = { };
int isValid = 0;
while (isValid == 0) {
scanf("%5s", str);
if (strlen(str) > 4) {
printf("Please enter a number within 1-1000: ");
char c = 0;
while ((c = getchar()) != '\n' && c != EOF);
}
char *endptr = NULL;
*inputInteger = strtol(str, &endptr, 10);
errno = 0;
if (str == endptr) {
printf("Not an integer.");
}
if (errno != 0) {
printf("Not an integer, errored.\n");
}
if ((strtol(str, &endptr, 10) >= 1) && (strtol(str, &endptr, 10) <= 1000)) {
isValid = 1;
}
else {
printf("Something wrong with input");
printf("%s", str);
}
}
printf("%s", str);
}
Every time I test my program by typing values such as 11111, it throws up the else condition saying something is wrong, immediately after saying values are too long. I don't want two errors - I have a feeling I'm not flushing a buffer properly but I have no idea how to do this and what to change.
Values like 111, and 1000 work.
Could someone please help me edit my code to fix this? Thank you!
-
> char str[5]
You need to make this larger, if you want to allow invalid input and have a chance to validate it.
> scanf("%5s", str);
Or more specifically, the number here needs to be one less than the size of your array.
-
Quote:
Originally Posted by
isaidilytd
I don't want two errors
You have a bunch of tests like:
Code:
if (something)
print(message)
if (otherthing)
print(message)
When more than one of the something/otherthing conditions are true, you will get more than one message.
To avoid this, use if/else if/else if/.../else for your tests. That way the branches will be exclusive of each other and only one of them will print a message.
Code:
if (something)
print(message)
else if (otherthing)
print(message)
else
print("all ok");