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!