I'm making a function to validate an integer within a domain and ask the user to type again if the number is out of range or if they typed in a character(or string of characters) or if they typed in more than just an integer. The code looks like this:
#include <stdio.h>
#include <time.h>
#include <conio.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
//\input stream clear function\*
void clear()
{
char c;
while((c=getchar())!='\n'&&(c=getchar())!=EOF){}
}
//getchar(char str[], min, max)
int GetInt(char msg[], int min, int max)
{
int value;
int rc;
char ovflow;
while (true)
{
printf("%s", msg);
rc = scanf("%d%c",&value,&ovflow);
if(rc == 0 || rc == 1)
{
printf("**No input accepted!**\n\n");
clear();
}
else if(ovflow != '\n')
{
printf("**Trailing characters!**\n\n");
clear();
}
else if(value < min || value > max)
{
printf("**Out of range!**\n\n");
}
else break;
}
return value;
}
int main()
{
int value=GetInt("enter value: ",2,20);
return 0;
}
Things work fine but when I typed in "something", the program froze until I press another Enter. It should look like this:
It froze if I typed in some certain string
It should still print the printf("%s", msg);
and immediately prompt for more input. I could guess it was because of clear()
function but whatever I tried, I could not fix it. I would be thankful if you can help me with this.
The answer is to just call getchar()
once. ex:
((c = getchar()) != '\n' && c != EOF) {}