+ 2
What will be the output? If user enter character instead of integer?
int turn=0; while(1) { printf("Enter your choice for toss\n1. Head\n2. Tail\n"); scanf("%d", &turn); if(turn==1||turn==2) { break; } else { printf("Invalid choice \n Please re-enter your choice.\n"); } }
7 Réponses
+ 1
#include <stdio.h>
int main() {
int turn=0;
while(1)
{
printf("Enter your choice for toss\n1. Head\n2. Tail\n");
scanf("%d", &turn);
if(turn==1||turn==2)
{
printf("input Match");
break;
}
else
{
printf("Invalid choice \n Please re-enter your choice.\n");
// if input is not integer , then this will read (consume) until next next line or space or End of Input
while((turn = getc(stdin)) != EOF && turn != '\n' && turn != ' ');
// getc() reads a character
}
}
return 0;
}
// hope it helps...
+ 2
Actually I don't know why when I'm writing the above code and inputting a character value it's going into an infinite loop
+ 2
Oky can you please suggest me right code ..all I want to display same MSG till the user inputs the right integer value...also keep that in mind that if the user inputs character or float or double it's should display a warning message with another chance to input
+ 2
Thanku sir😊
+ 1
%d looks for an integer input so on no integer input, it will not take any input to turn.
I think, you may have any other specific doubt related to this ..!!?
+ 1
Because turn will remain 0
Other than, until input 1 or 2, it's infinite loop..
+ 1
You're welcome..