0

Why does this loop execute infintely

#include <iostream> // #include <algorithm> #include <cstring> #include <string_view> #include <stdio.h> using namespace std; int main() { char selection; // grade entered by user cout << " Enter selection" << endl; selection = std::getchar(); while ((selection != 'X')){ switch ( selection ) // switch statement nested in while { case 'A':case 'a':// grade was uppercase A cout<< "Ok" <<endl; break; case 'B': case 'b': cout<< "Ok" <<endl; break; case 'C':case 'c': cout<< "ok" <<endl; break; // exit switch case 'D':case 'd': // grade was uppercase D // or lowercase d cout<< "bad" <<endl; break; // exit switch case 'F': case 'f':// grade was uppercase F // or lowercase f cout<< "bad" <<endl; break; // exit switch default: cout << " Exit the program" << endl; } } return 0; }

3rd Nov 2021, 2:03 PM
Reynolds Onyango
Reynolds Onyango - avatar
4 Respostas
+ 1
If input is not X it will run infinitely cause you haven't put any exit condition nor more input option after the switch statement. Put the input option just before the while loop end. In this case when you enter X, loop will break.
3rd Nov 2021, 2:11 PM
Kashyap Kumar
Kashyap Kumar - avatar
+ 1
Reynolds Onyango Please provide the link to the code so that I can run and modify.
3rd Nov 2021, 7:12 PM
Kashyap Kumar
Kashyap Kumar - avatar
0
Ok when i do that it works but still one problem it displays the default option too " Exit the program" even when a,b,c,d,f options are entered
3rd Nov 2021, 2:20 PM
Reynolds Onyango
Reynolds Onyango - avatar
0
x
3rd Nov 2021, 5:08 PM
فرید طاووسی
فرید طاووسی - avatar