Answer on Question #62455 , Programming & Computer Science / C
How to print only one time the statement if a few wrong input is key in:
Eg:
if key in kkk, only will print one statement instead of the example below.
sample output:
Do you wish to try again (Type Y to continue Q to quit:kkk
Error: Invalid choice
Do you wish to try again (Type Y to continue Q to quit:Error: Invalid choice
Do you wish to try again (Type Y to continue Q to quit:Error: Invalid choice
Do you wish to try again (Type Y to continue Q to quit:
//Code
valid=0;
while (valid==0)
{
printf("\nDo you wish to try again (Type Y to continue Q to quit:"); // print statement request for input
scanf("%c", &choice); // get user input
choice = toupper(choice);
if((choice == 'Y') || (choice == 'Q')) valid= 1;
else printf("Error: Invalid choice\n"); // statement
}
Answer:
If you want to print only one time the statement if a few wrong input is entered, you have to clear stdin stream (read all symbols from it).
First method is to use fflush(stdin);
Second method is to read all symbols from the stdin stream using loop^
do {
choice = getchar();
} while (choice != '\n' && choice != EOF);
So you have to change your code like below:
Method 1
valid=0;
while (valid==0)
{
printf("\nDo you wish to try again (Type Y to continue Q to quit:"); /* print statement request for input */
scanf("%c", &choice); /* get user input */
choice = toupper(choice);
if((choice == 'Y') || (choice == 'Q'))
valid = 1;
else
{
printf("Error: Invalid choice\n"); /* statement */
fflush(stdin);
}
}Method 2
valid=0;
while (valid==0)
{
printf("\nDo you wish to try again (Type Y to continue Q to quit:"); /* print statement request for input */
scanf("%c", &choice); /* get user input */
choice = toupper(choice);
if((choice == 'Y') || (choice == 'Q'))
valid = 1;
else
{
printf("Error: Invalid choice\n"); /* statement */
do {
choice = getchar();
} while (choice != '\n' && choice != EOF);
}
}http://www.AssignmentExpert.com