+ 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"); } }

21st Jun 2022, 5:18 PM
Saima Shamim
Saima Shamim - avatar
7 ответов
+ 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...
21st Jun 2022, 7:57 PM
Jayakrishna 🇮🇳
+ 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
21st Jun 2022, 6:53 PM
Saima Shamim
Saima Shamim - avatar
+ 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
21st Jun 2022, 7:12 PM
Saima Shamim
Saima Shamim - avatar
+ 2
Thanku sir😊
21st Jun 2022, 8:33 PM
Saima Shamim
Saima Shamim - avatar
+ 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 ..!!?
21st Jun 2022, 5:55 PM
Jayakrishna 🇮🇳
+ 1
Because turn will remain 0 Other than, until input 1 or 2, it's infinite loop..
21st Jun 2022, 7:00 PM
Jayakrishna 🇮🇳
+ 1
You're welcome..
21st Jun 2022, 8:42 PM
Jayakrishna 🇮🇳