Reputation: 1
I want to get the user to select a choice. So I declared a variable named Choice and I want it to input a char
that can only be 'M'
, 'C'
, 'O'
or 'P'
.
This is my code :
char Choice;
printf("Select something to do :\n'M':Model Parametering\n'C':Calendar creation\n'O':Calendar Output\n'P':Calendar Print\nChoice==>>");
Choice = getchar();
while(Choice!='M' && Choice != 'C' && Choice != 'O' && Choice != 'P'){
printf("\nIncorrect choice, Try again\n");
printf("Select something to do :\n'P':Model Parametering\n'C':Calendar creation\n'O':Calendar Output\n'P':Calendar Print\nChoice==>>");
Choice = getchar();}
The thing is when I test it with a wrong value (inputting a character that is NOT in ['M','C','O','P']
, the while loop works more than once.
For example if I input "TEST"
instead of 'M'
, 'C'
, 'O'
or 'P'
the while works 5 times not only once like I want!
Why is this happening?
Upvotes: 0
Views: 79
Reputation: 7923
After entering TEST
(4 character worth), you also pressed Enter. This is the fifth character (newline, really) passed to your program. Same way, after doing a single character (and Enter), the loop runs twice - first for the character itself, then for a newline.
Upvotes: 1
Reputation: 375
getchar() considers a character individually from stdin.By providing the input as "TEST", it first reads 'T' , loops again, reads E, loops again, reads S and so on, until it can ask for another character again, which is the 5th loop.
Upvotes: 0
Reputation: 27240
You have given input TEST
it has 4 character so stdin has 4 character so 4 times getchar()
can execute. then on next getchar()
it will again wait for next input from stdin.
Upvotes: 0