This is stuck in an infinite loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

This is stuck in an infinite loop

#include <iostream> using namespace std; int main() { int k = 0; enum CompanyRole {EXECUTIVE = 1, MANAGER = 2, STAFF = 3}; cin >> k; while((k != 1) || (k!=2) || (k!=3)){ switch(k) { case EXECUTIVE: cout << "Executive\n"; break; case MANAGER: cout << "Manager\n"; break; case STAFF: cout << "Staff\n"; break; default: cout << "Wrong role. Enter again.\n"; break; } std::cin >> k; } return 0;

27th Feb 2018, 2:57 AM
Chuck
Chuck  - avatar
9 Answers
+ 1
Do you want to exit from the while loop with a switch case?
27th Feb 2018, 3:09 AM
teKno23
teKno23 - avatar
+ 1
Move the switch out of the while loop
27th Feb 2018, 3:15 AM
teKno23
teKno23 - avatar
0
when I type in 1-3, I want it to print the corresponding message and stop there. when I type in any other number, I want it to loop until I type 1-3
27th Feb 2018, 3:12 AM
Chuck
Chuck  - avatar
0
my instructions call for the switch case to be inside a while loop
27th Feb 2018, 3:16 AM
Chuck
Chuck  - avatar
0
Try to put cin >> k inside the default switch case, before the break
27th Feb 2018, 3:18 AM
teKno23
teKno23 - avatar
0
1, 2, 3 still cause infinite loop. And I am getting time limit exceeded
27th Feb 2018, 3:23 AM
Chuck
Chuck  - avatar
0
I would make a boolean allow =True as while condition. boolean allow = true; While(allow) { cin>>k; switch (k) { Case 1: cout << "Case1; allow = false; //to break the loop, same with case 2-3 } }
27th Feb 2018, 3:30 AM
teKno23
teKno23 - avatar
0
so I have this: 1-3 works good now, other numbers cause indefinite loop #include <iostream> using namespace std; int main() { int k = 0; enum CompanyRole {EXECUTIVE = 1, MANAGER = 2, STAFF = 3}; bool allow = true; while(allow) { cin>>k; switch (k) { case 1: cout << "Case1 \n"; allow = false; break; case 2: cout << "Case2 \n"; allow = false; break; case 3: cout <<"Case3 \n"; allow = false; break; default: cout << "try again \n"; cin >> k ; break;//to break the loop, same with case 2-3 std::cin >> k; } } return 0; }
27th Feb 2018, 3:50 AM
Chuck
Chuck  - avatar
0
Remove the cin>>k inside the switch, you are also waiting for user input at starting of each while loop
27th Feb 2018, 12:52 PM
teKno23
teKno23 - avatar