Reputation: 291
I have a project that must be made only in C (I'm not allowed to use C++). Right now I'm working on the UI (a little menu showed in the console, each option has a number from 0 to 6 assigned to it, the user typed the number, hits enter and so on).
I'm having a problem with the reading option function.
At first I tried
int option;
scanf("%d", &option);
but this caused problems when I typed in characters.
I tried reading a char:
char option;
scanf("%s", &option);
option -= '0';
This allowed me to treat it like a number and worked nice for the first tests, allowing me to verify if the option is valid (it's not a letter, it's a number between 0 and 6).
The problem is that I can type more than one character and all of them will be stored somewhere in memory. And that's obviously bad.
I tried reading with "%c"
, but that will display the error message for every character in the string I entered.
To make it a bit more clear, this is the function
int readOption(int maxOp)
{
char option = -1;
while(option < 0 || option > maxOp)
{
scanf("%c", &option);
option -= '0';
if(option < 0 || option > maxOp)
printf("Invalid option!\nTry again: \n");
}
return option;
}
If I type "abc
", the error message will be printed 3 times.
So how can I make sure that any extra characters entered are ignored?
Upvotes: 0
Views: 4192
Reputation: 179
You can use getc()
to do the job like this:
int main(){
char choice = getc(stdin);
fflush(stdin);
}
Now choice
is the first entered character, everything entered after the first character is deleted so it won't interrupt any other user inputs.
In general, when the user enters input it's stored in a special buffer called stdin
, if you don't delete that buffer after reading the first character using fflush(stdin)
it will interrupt any future user inputs.
Upvotes: 0
Reputation: 1564
Untested, buy you may try something like this:
scanf(" %[0-6]1d*[^\n]", &option);
The call to scanf
will only be valid if the input is a single number between 0 and 6, ignoring leading spaces. *
suppresses any character after that isn't in this range and that is not a newline.
Upvotes: 0
Reputation: 106042
Try this
int ch;
scanf(" %c", &option);
while((ch = getchar()) != '\n');
Upvotes: 2