Trying to find out why my code keeps infinite looping - c++

I am very new to programming so pardon my lack of knowledge. I am trying to create a simple menu in which I am going to execute a few problems by pressing 1,2,3 etc. but my code keeps looping over and over again and I can't understand why.
int main()
{
int choice;
do
{
cout << "\t|--------------------------- Menu ---------------------------|" << endl;
cout << "1.|- Добавяне на телефонни номера -|" << endl;
cout << "2.|- Извеждане на всички телефонни абонати на екрана -|" << endl;
cout << "3.|- Месечно потребление -|" << endl;
cout << "4.|- Изчисление на месечна такса -|" << endl;
cout << "5.|- Справки за абонатите с под меню -|" << endl;
cout << "6.|- Край на програмата -|" << endl;
switch(choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
cout << "|- Благодаря ви -|" << endl;
return 0;
}
}
while(choice != 6);
}

You need to use cin in your code in order to change what choice is every time that you go through the loop. Also it is a good idea to handle invalid user inputs. This is done by (!(cin >> choice)) until input will return true. While this is the case you want to cin.clear() and cin.ignore() to reset the state of the stream so that you can keep asking the user for a correct input.
#include<iostream>
using namespace std;
int main()
{
// it is a good idea to initialize the variable when you create it
int choice = 0;
do
{
cout << "\t|--------------------------- Menu ---------------------------|" << endl;
cout << "1.|- Добавяне на телефонни номера -|" << endl;
cout << "2.|- Извеждане на всички телефонни абонати на екрана -|" << endl;
cout << "3.|- Месечно потребление -|" << endl;
cout << "4.|- Изчисление на месечна такса -|" << endl;
cout << "5.|- Справки за абонатите с под меню -|" << endl;
cout << "6.|- Край на програмата -|" << endl;
// this loop will handle incorrect inputs from the user
// for example entering a char, when the stream is expecting an int
while (!(cin >> choice))
{
cin.clear();
cin.ignore();
cout << "Please enter a valid choice: ";
cin >> choice;
}
switch (choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
cout << "|- Благодаря ви -|" << endl;
return 0;
}
} while (choice != 6);
}

Related

why my program running continously and not stoping?

I'm trying to make an template which is my class assignment.
I used a switch statement in the do while loop while the condition is if enter variable not equal to 16 you should terminate the program
I'vve already used break statment in every case but it isn't working
#include <iostream>
using namespace std;
int main()
{
int op;
cout << "Please enter choice between 1 to 15 For Different Operations "
<< endl;
cout << "1. Create List(create a new list(presumably empty))" << endl;
cout << "2. Insertion" << endl;
cout << "3. Deletion" << endl;
cout << "4. Update(replace the element)" << endl;
cout << "5. Start" << endl;
cout << "6. Next" << endl;
cout << "7. Back" << endl;
cout << "8. Tail" << endl;
cout << "9. Find" << endl;
cout << "10. Copy" << endl;
cout << "11. Get(display current index and element)" << endl;
cout << "12. Size / length" << endl;
cout << "13. Display list" << endl;
cout << "14. De - allocate list" << endl;
cout << "15. Exit" << endl;
cin >> op;
do {
switch (op) {
case 1:
cout << "Creating the List" << endl;
break;
case 2:
cout << "inserting... " << endl;
break;
case 3:
cout << "Deleting... " << endl;
break;
case 4:
cout << "updating... " << endl;
break;
case 5:
cout << "starting... " << endl;
break;
case 6:
cout << "next... " << endl;
break;
case 7:
cout << "back... " << endl;
break;
case 8:
cout << "Tail... " << endl;
break;
case 9:
cout << "Find... " << endl;
break;
case 10:
cout << "Copying... " << endl;
break;
case 11:
cout << "Getting... " << endl;
break;
case 12:
cout << "Size... " << endl;
break;
case 13:
cout << "Display... " << endl;
break;
case 14:
cout << "Deallocate... " << endl;
break;
case 15:
terminate;
break;
default:
cout << "Please enter the correct choice " << endl;
break;
}
} while (op != 16);
return 0;
}
i expect the the cout output in every choice user made and then stop for taking input
from your original code
cin >> op;
do {
switch (op)
so you read from cin outside the loop and never read again, reordering so you read at every loop pass will ask you again the desired operation
do {
cin >> op;
switch (op)
Additionally note that break does not break the loop it just breaks from the switch. Without the break the instructions from the next case will be executed as well in the switch.
If you want to break from the loop under some conditions you need to add a break outside of the switch statement, you can use a variable to "remember" if you should leave the loop.
However since you have an exit condition in your typed instructions why not make the loop exit
} while (op != 15);
which seems to make sense because of the
cout << "15. Exit" << endl;
line.

C++: Printing A List

The code below contains a table I created numbering from 1 to 10 in reverse order. (This is the code without breaks, later changed.)
#include <iostream>
using namespace std;
int main()
{
switch(1) {
case 1: cout << "1. blue" << endl;
case 2: cout << "2. orange.." << endl;
case 3: cout << "3. yellow.." << endl;
case 4: cout << "4. green.." << endl;
case 5: cout << "5. purple.." << endl;
case 6: cout << "6. red.." << endl;
case 7: cout << "7. teal.." << endl;
case 8: cout << "8. aqua.." << endl;
case 9: cout << "9. white.." << endl;
case 10: cout << "10. gray.." << endl;
}
}
I am trying to make it so that each time the loop runs, the program will output the message corresponding to the next lower number, one by one. (Code with breaks)
#include <iostream>
using namespace std;
int main() {
for(int i = 10; i>0; --i){
switch(i) {
case 1: cout << "1. blue" << endl;
break;
case 2: cout << "2. orange.." << endl;
break;
case 3: cout << "3. yellow.." << endl;
break;
case 4: cout << "4. green.." << endl;
break;
case 5: cout << "5. purple.." << endl;
break;
case 6: cout << "6. red.." << endl;
break;
case 7: cout << "7. teal.." << endl;
break;
case 8: cout << "8. aqua.." << endl;
break;
case 9: cout << "9. white.." << endl;
break;
case 10: cout << "10. gray.." << endl;
break;
}
}
}
I am having trouble looping down the list, and listing each number/color one by one.
At the end of listing each item, I would like the program to ask the user if they would like to Stop, or Restart the loop.
You need to create a variable to hold the variable that will be passed into your switch statement. Your switch statement needs to start from 10 and go down because you want to print case 10 first.
#include <iostream>
using namespace std;
int main() {
for(int i = 10; i>0; --i){
switch(i) {
case 1: cout << "1. blue" << endl;
break;
case 2: cout << "2. orange.." << endl;
break;
case 3: cout << "3. yellow.." << endl;
break;
case 4: cout << "4. green.." << endl;
break;
case 5: cout << "5. purple.." << endl;
break;
case 6: cout << "6. red.." << endl;
break;
case 7: cout << "7. teal.." << endl;
break;
case 8: cout << "8. aqua.." << endl;
break;
case 9: cout << "9. white.." << endl;
break;
case 10: cout << "10. gray.." << endl;
break;
}
}
}
It was a bit confusing how you were explaining before, I think i got it now.
As said on the comments switch works but probably isn't the best way, I will show you how I would do it, if you really want it done with switch just say in the comments and I will update my answer.
I think what you really want is to print one option and after ask if the user wants to stop or start from the beginning, if not just continue (Just comment if it isn't this).
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<string, 10> colors {"1. blue", "2. orange..", "3. yellow..", "4. green..", "5. purple..", "6. red..", "7. teal..", "8. aqua..", "9. white..", "10. gray.."};
for(int i = colors.size() - 1; i >= 0; --i)
{
cout << colors[i] << endl;
cout << endl << "Would you like to stop[s/S] or restart[r/R]?: ";
char input;
if (cin >> input)
{
if (tolower(input) == 's')
break;
else if (tolower(input) == 'r')
i = colors.size(); // To restart should be one more than the last index, it's going to be decreased at the end of loop
}
cout << endl;
}
}
So basically the code has two parts, first the printing which I changed the switch statement to and array.
array<string, 10> colors {"1. blue", "2. orange..", "3. yellow..", "4. green..", "5. purple..", "6. red..", "7. teal..", "8. aqua..", "9. white..", "10. gray.."};
for(int i = colors.size() - 1; i >= 0; --i)
{
cout << colors[i] << endl;
}
So this way you could even add more to the array and the code would still work, just starts at the end of the array and prints one by one.
The second part is were it asks the user if he wants to stop or restart.
char input;
if (cin >> input)
{
if (tolower(input) == 's')
break;
else if (tolower(input) == 'r')
i = colors.size(); // To restart should be one more than the last index, it's going to be decreased at the end of loop
}
If the user types s just breaks out of the loop, if he types r resets the i variable to the last index of the array (although the array is indexed at 0, you can't put size() - 1 because at the end of the loop the variable i is decreased).
As requested here is the switch version
#include <iostream>
using namespace std;
int main()
{
while (true)
{
for(int i = 10; i>0; --i)
{
switch(i)
{
case 1: cout << "1. blue" << endl;
break;
case 2: cout << "2. orange.." << endl;
break;
case 3: cout << "3. yellow.." << endl;
break;
case 4: cout << "4. green.." << endl;
break;
case 5: cout << "5. purple.." << endl;
break;
case 6: cout << "6. red.." << endl;
break;
case 7: cout << "7. teal.." << endl;
break;
case 8: cout << "8. aqua.." << endl;
break;
case 9: cout << "9. white.." << endl;
break;
case 10: cout << "10. gray.." << endl;
break;
}
}
cout << endl << "Would you like to stop[s/S] or restart[r/R]?: ";
char input;
if (cin >> input && tolower(input) != 'r')
break;
cout << endl;
}
}
I want to suggest a different approach to solve your problem.
Think of what you are trying to do and use one or more function calls to do that from main instead of having the code inside main. You core functionality is to print a color given an integer value.
From main, that would look like:
void printColor(int i);
int main()
{
for (int i = 10; i>0; --i)
{
printColor(i);
}
}
In the implementation of printColor, you would use:
std::string getColor(int i);
void printColor(int i)
{
std::cout << i << ". " << getColor(i) << std::endl;
}
You can implement getColor as:
std::string getColor(int i)
{
switch (i)
{
case 1:
return "blue";
case 2:
return "orange";
...
}
// If value is different than the known values in the switch statement,
// we have an unknown color
return "Unknown";
}
For repeating the core function in main, you can use a while loop.
Here's everything put together.
#include <iostream>
#include <string>
void printColor(int i);
std::string getColor(int i);
bool getRepeat();
int main()
{
bool repeat = true;
while ( repeat )
{
for (int i = 10; i>0; --i)
{
printColor(i);
}
repeat = getRepeat();
}
}
void printColor(int i)
{
std::cout << i << ". " << getColor(i) << std::endl;
}
std::string getColor(int i)
{
switch (i)
{
case 1:
return "blue";
case 2:
return "orange";
case 3:
return "yellow";
case 4:
return "green";
case 5:
return "purple";
case 6:
return "red";
case 7:
return "teal";
case 8:
return "aqua";
case 9:
return "white";
case 10:
return "gray";
}
// If value is different than the known values in the switch statement,
// we have an unknown color
return "Unknown";
}
bool getRepeat()
{
std::cout << "Stop or Continue (S/C)? ";
char c;
std::cin >> c;
return (c == 'c' || c == 'C');
}

Functional Loop with user input C++

So I got an assignment to make a program that allows the user to select three favourite destinations in order. It repeats until the user decides to stop. Once the user decides to discontinue, the program then displays the total votes received for each destination according to preference by the users. One user will have three preferences and if the program repeats four times, it means four users’ preferences are recorded. Therefore a total of 12 preferences are recorded in this instance.
I have tried to limit input for the loop to work but it seems it will only work with a decision which is not necessary at the beginning of the program, which i want to remove altogether.
Also, I have tried to limit output for each of the decisions but it will only run once and then move on to the next choice. Is there any way to get a persistent entry prompt that will only continue after a valid input.
Lastly, is there any way I could improve the code by using switch/break statements instead of if/else?
Here's my code:
cout << "Do you want to go forth with this program?\nType y to confirm. The
program will exit if anything else is entered: ";
cin >> Decision;
while (Decision=="y")
{
cout << "\n\nNow please enter the code for which your destination corresponds to: " << endl; //first decision
cin >> Choice1;
if (Choice1 == 1)
{
LasVegas1++;
}
else if (Choice1 == 2)
{
Tokyo1++;
}
if (cin.fail())
{
cout << "Please enter a valid choice" << endl;
continue;
}
cout << " \nNow please enter the second code: " << endl; //second decision
cin >> Choice2;
if (Choice2 == 1)
{
LasVegas2++;
}
else if (Choice2 == 2)
{
Tokyo2++;
}
else
{
cout << "\nError! Please enter a valid code as shown above!\n";
cout << "\nNow please enter the second code: ";
cin >> Choice2;
}
cout << " \nNow please enter the third code: " << endl; //third decsion
cin >> Choice3;
if (Choice3 == 1)
{
LasVegas3++;
}
else
{
cout << "\nError! Please enter a valid code as shown above!\n";
cout << "\nNow please enter the third code: ";
cin >> Choice3;
}
cout << " \nDo you wish to select three more destinations? (Y/N): " << endl;
cin >> Decision;
}
What I would do is to put all your city variables into an array and then convert your three sets of code into a for loop. Something like:
for(int i = 0; i < 3; i++) {
if(Choice1 == 0) {
rome[i]++;
}
//etc
So that way you wouldn't need to repeat the same code three times. Also you only need one Choice variable. (You can just reset it at each iteration of the loop)
Additionally you could implement a switch statement to clean up the code a little:
switch(Choice1) {
case 1:
LasVegas1++;
break;
case 2:
Tokyo1++;
break;
case 3:
London1++;
break;
case 4:
Paris1++;
break;
case 5:
Dubai1++;
break;
case 6:
Mumbai1++;
break;
case 7:
NewYork1++;
break;
case 8:
Sydney1++;
break;
case 9:
Auckland1++;
break;
case 10:
Rome1++;
break;
case 11:
Other1++;
break;
}
It can be heavily simplified by the use of "Switch" and "Break".
Like the code that i have written. Have a look :
char input;
int choice;
void Permission() {
cout << "Do you want to go forth with this program ? (y to confirm)" << flush;
cin >> input;
cout << endl;
}
void Decision1() {
if(input == 'y') {
cout << "Now please enter the code for which your destination corresponds to : " << flush;
cin >> choice;
switch (choice) {
case 1:
cout << "LasVegas " << endl;
break;
case 2:
cout << "Tokyo " << endl;
break;
case 3:
cout << "London " << endl;
break;
case 4:
cout << "Paris " << endl;
break;
case 5:
cout << "Dubai " << endl;
break;
case 6:
cout << "Mumbai " << endl;
break;
case 7:
cout << "New York " << endl;
break;
case 8:
cout << "Sydney " << endl;
break;
case 9:
cout << "Auckland " << endl;
break;
case 10:
cout << "Rome " << endl;
break;
case 11:
cout << "Other " << endl;
break;
default:
cout << "Invalid option. Enter Again : " << flush;
cin >> choice;
}
cout << endl;
}
}
void Decision2() {
cout << "Now please enter the second code: " << flush;
cin >> choice;
switch (choice) {
case 1:
cout << "LasVegas " << endl;
break;
case 2:
cout << "Tokyo " << endl;
break;
case 3:
cout << "London " << endl;
break;
case 4:
cout << "Paris " << endl;
break;
case 5:
cout << "Dubai " << endl;
break;
case 6:
cout << "Mumbai " << endl;
break;
case 7:
cout << "New York " << endl;
break;
case 8:
cout << "Sydney " << endl;
break;
case 9:
cout << "Auckland " << endl;
break;
case 10:
cout << "Rome " << endl;
break;
case 11:
cout << "Other " << endl;
default:
cout << "Invalid option. Enter Again : " << flush;
cin >> choice;
}
cout << endl;
}
void Decision3() {
cout << "Now please enter the third code: " << flush;
cin >> choice;
switch (choice) {
case 1:
cout << "LasVegas " << endl;
break;
case 2:
cout << "Tokyo " << endl;
break;
case 3:
cout << "London " << endl;
break;
case 4:
cout << "Paris " << endl;
break;
case 5:
cout << "Dubai " << endl;
break;
case 6:
cout << "Mumbai " << endl;
break;
case 7:
cout << "New York " << endl;
case 8:
cout << "Sydney " << endl;
break;
case 9:
cout << "Auckland " << endl;
break;
case 10:
cout << "Rome " << endl;
break;
case 11:
cout << "Other " << endl;
break;
default:
cout << "Invalid option. Enter Again : " << flush;
cin >> choice;
}
cout << endl;
}
int main() {
Permission();
Decision1();
Decision2();
Decision3();
system("PAUSE");
return 0;
}
I don't know that how to get the loop at the default when the user enters the wrong option. I was able to give the "cin" once. Update this problem if you know how to.
Yes you could improve with a switch statement. Theres also something called a do while loop you should look into.

C++: Looping Menu Switch

I have an assignment where I have to have a menu which is somewhat working, it can't crash or exit if I type in the wrong input and it can't have an endless loop. Although my menu doesn't exits or crashes it goes in to an endless loop where if I type in anything but an integer. Here is my code.
void mainMenu()
{
int option;
cout << "\t\t\t***** Project: Algorithms *****\n\n\n";
cout << "Enter your selection.\n\n";
cout << "1\tSearches.\n";
cout << "2\tCalculations and negations.\n";
cout << "3\tCopying.\n";
cout << "4\tExit the program.\n";
cout << "Please enter the menu next to each option.\n> " << flush;
cin >> option;
switch (option)
{
case 1: cout << "Yes!";
system("cls");
searchMenu();
break;
case 2: cout << "Yes!";
system("cls");
Calc_NegateMenu();
break;
case 3: cout << "Yes!";
system("cls");
copyMenu();
break;
case 4: cout << "Yes!";
exit(0);
break;
default: cout << "ERROR! Invalid input!";
system("cls");
mainMenu();
break;
}
}
The other menus.
void searchMenu()
{
int option;
cout << "\t\t\t***** Search *****\n\n\n";
cout << "Enter your selection.\n\n";
cout << "1\tSearch for a element with find.\n";
cout << "2\tSearch for an element with binary search.\n";
cout << "3\tSearch for pair elements.\n";
cout << "4\tBack to the main menu.\n";
cout << "Please enter the menu next to each option.\n> " << flush;
cin >> option;
switch (option)
{
case 1: cout << "Yes!";
system("cls");
searchMenu();
break;
case 2: cout << "Yes!";
system("cls");
Calc_NegateMenu();
break;
case 3: cout << "Yes!";
system("cls");
copyMenu();
break;
case 4: cout << "Yes!";
system("cls");
copyMenu();
break;
default: cout << "ERROR! Invalid input!";
system("cls");
mainMenu();
break;
}
}
void Calc_NegateMenu()
{
int option;
cout << "\t\t\t***** Calculate or Negate *****\n\n\n";
cout << "Enter your selection.\n\n";
cout << "1\tCalculate the total sum of all elements in the vector.\n";
cout << "2\tNegate all elements in the vector.\n";
cout << "3\tBack to the main menu.\n";
cout << "Please enter the menu next to each option.\n> " << flush;
cin >> option;
switch (option)
{
case 1: cout << "Yes!";
system("cls");
searchMenu();
break;
case 2: cout << "Yes!";
system("cls");
Calc_NegateMenu();
break;
case 3: cout << "Yes!";
system("cls");
mainMenu();
break;
default: cout << "ERROR! Invalid input!";
system("cls");
mainMenu();
break;
}
}
void copyMenu()
{
int option;
cout << "\t\t\t***** Copy *****\n\n\n";
cout << "Enter your selection.\n\n";
cout << "1\tCopy to list.\n";
cout << "2\tCopy to file.\n";
cout << "3\tBack to the main menu.\n";
cout << "Please enter the menu next to each option.\n> " << flush;
cin >> option;
switch (option)
{
case 1: cout << "Yes!";
system("cls");
searchMenu();
break;
case 2: cout << "Yes!";
system("cls");
Calc_NegateMenu();
break;
case 3: cout << "Yes!";
system("cls");
mainMenu();
break;
default: cout << "ERROR! Invalid input!";
system("cls");
mainMenu();
break;
}
}
When cin to an integer doesn't find one it sets an error flag and does not read from the input until the flag is cleared.
See this answer or this one.
Search on "cin infinite loop" and read the cin documentation.

C++ Switch Statement - Giving player another chance to choice

This is a block of code from a book I've been studying and trying to improve upon, but I'm having trouble finding a way to give the player another chance at selecting the difficulty after entering the default choice. This is a very simple console text-based game and when the player chooses an incorrect choice, the game doesn't allow the player to re-choose.
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n\n";
int choice;
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "You picked Easy\n";
break;
case 2:
cout << "You picked Normal\n";
break;
case 3:
cout << "You picked Hard\n";
break;
default:
cout << "Your choice is invalid.\n";
}
system("pause");
return 0;
}
You can refactor the switch into a function, which can be called whenever the player wants to change their difficulty choice.
int choose()
{
int choice;
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n\n";
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "You picked Easy\n";
break;
case 2:
cout << "You picked Normal\n";
break;
case 3:
cout << "You picked Hard\n";
break;
default:
cout << "Your choice is invalid.\n";
choice = 0; //this will signal error
}
return choice;
}
int _tmain(int argc, _TCHAR* argv[])
{
int choice = 0;
while(choice == 0){choice = choose();};
system("pause");
return 0;
}
Now whenever the player decides to change difficulty (maybe they enter a special letter) you can use choice = choose() to alter the difficulty.
Wrap the input code in a do-while.
bool valid = true;
do
{
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "You picked Easy\n";
break;
case 2:
cout << "You picked Normal\n";
break;
case 3:
cout << "You picked Hard\n";
break;
default:
cout << "Your choice is invalid.\n";
valid = false;
}
} while(!valid);