do while loop with nested if statements not exiting in c++ - c++

OKay, so I'm new to the whole do while loop thing, and I'm trying to make a main menu, here's my code below:
int main()
{
int choice;
char sure;
bool quit = false;
char ctrl;
do
{
cout << "Main Menu." << endl
<< "1. New Game." << endl
<< "2. Load Game." << endl
<< "3. Exit." << endl
<< "Your choice: ";
cin >> choice;
if (choice == 1)
{
cout << "Are you sure you wish to start a new game? (Y/N) ";
cin >> sure;
if (sure != 'N' || sure != 'n')
{
ctrl = 'a';
quit = true;
}
}
else if ( choice == 2)
{
ctrl = 'b';
quit = true;
}
else
quit = true;
}
}
while (quit == true);
if (ctrl = 'a')
cout << "New Game." << endl;
else if (ctrl = 'b')
cout << "Load Game." << endl;
else
cout << "Goodbye." << endl;
return 0;
}
there are a few getchar() thrown in there. But the only problem is as you'll probably figure out is that after I do everything it just restarts again, and not exit the loop. What is the problem in the code?
Thanks

I think you meant while (quit != true);
And remember, comparison is done with ==, if (ctrl = 'a') assigns 'a' to ctrl..

You are not setting quit to false anywhere and your loop runs while quit equals true. You need to get the meaning of your boolean values straight or simply change the while part to while(!quit). I'd rather to the first.

Shouldn't you just change
while (quit == true);
to
while (quit != true);
?
Maybe you know it, but I'll just repeat how
do{
//...
} while(condition)
loop works. You iterate until the condition is false. In your case it was always true, that's why you had an infinite loop.
P.S. Take a loot at this answer also. Yet another error was described there.
Imroved code with hopefully all corrected mistakes is here.

Related

calling function on while loop

I'm making a calculator program but I already encounter a problem. Well, my code is in a loop that will call a function to display the choices and then ask the user to pick, a/s/m/d are the choices. If the input is on the choices, it will proceed to the next step. Otherwise, it will loop and then call the function again.
#include <iostream>
using namespace std;
void home()
{
cout << "\nChoose your operation:" << endl;
cout << "\tType [A] for Addition" << endl;
cout << "\tType [S] for Subtraction"<< endl;
cout << "\tType [M] for Multiplication" << endl;
cout << "\tType [D] for Division" << endl;
}
int main()
{
char operation;
bool no_operator = true;
int design = 73;
for (int i = 0; i < design; i++){
if (i == 25){
cout << " WELCOME TO CALCULATOR ";
i += 22;
}
else i == 72 ? cout << "*\n" : cout << "*";
}
while (no_operator){
home();
cout << "\nOperation: ";
cin >> operation;
if (operation == 'A' || operation == 'a')
{
cout << "\nIt will going to add numbers";
no_operator = false;
}
else if (operation == 'S' || operation == 's')
{
no_operator = false;
cout << "\nIt will going to subtract numbers";
}
else if (operation == 'M' || operation == 'm')
{
no_operator = false;
cout << "\nIt will going to multiply numbers";
}
else if (operation == 'D' || operation == 'd')
{
no_operator = false;
cout << "\nIt will going to divide numbers";
}
else
{
cout << "\tInvalid Input: You must enter A/S/M/D only\n";
//home();
}
}
return 0;
}
My problem is it will run the '''home()''' in else statement even if the input is correct on the second loop.
I want to stop the '''home()''' to be called when the input is correct
Your code works perfectly fine. Make sure you're inputting the correct letters.
Also for this code, a "do while()" loop would be better.
You program is working perfectly fine as the input is correct it does not show the home rather print the message it will going to divide etc.

How to prompt user to re-loop the whole program?

I want the user to choose between playing the game again or ending the program, however when prompted, if they press 'y' the same thing gets repeated over and over instead of the whole program from the very beginning. I've tried while loops, do/while loops, if statements, rearranging the code, but nothing has worked. Any advice?
#include <iostream>
#include <string>
using namespace std;
int main(){
string animal = "fish";
string guess;
char choose = 'Y' ;
int count = 0;//keeps a running total of how many times the user
has guessed an answer.
int limit = 5;//allows user to guess only 5 times, otherwise
they loose the game.
bool out_of_guesses = false;//to check whether the user has run
out of guesses.
cout << "I am thinking of an animal.\n" << endl;
do{
while(animal != guess && !out_of_guesses){//Nested while
loop inside main loop to keep track of how many tries the user has
attempted and to validate their answers.
if(count < limit){
cout << "Can you guess what animal I am thinking of?: ";
getline(cin, guess);
count++;
if(animal != guess){
cout << "\nHmm, nope. That's not the animal I'm
thinking of." << endl;
if(count > 2 && count <5){
cout << "I'll give you a hint. It lives in
water." << endl;
}
}
}
else{
out_of_guesses = true;
}
}//End nested while loop
if(out_of_guesses){
cout << "\nI'm sorry, but you are out of guesses." <<
endl;
}
else{
cout << "\n*** Good job! You guessed the correct animal!
***" << endl;
cout << "\t\t><)))º> ❤ <º)))><\t\t" << endl;
}
//The do-while loop is there to ask the user if they wish to
play the game again.
cout << "Would you like to try again?(y/n): ";
cin >> choose;
if(choose == 'N' || choose == 'n')
break;
}while(choose == 'Y' || choose == 'y');
return 0;
}
The bool out_of_guesses = false; must be in-between while(true) and while(animal != guess && !out_of_guesses), and not outside the first while loop. Because our while loop condition is always false, and then it does enter it.
You should also reset your guess variable in-between those 2 loops, else same thing could happen (false while loop) in case of the answer is found.
Here the code with some refactoring/review, which I used the guess as upper case to handle any typography of the answer. I also removed the out of guess variable to use the count and limit one instead.
#include <iostream>
#include <string>
#include <cctype>
int main()
{
const std::string animal = "FISH";
const int limit = 5;
do
{
std::cout << "I am thinking of an animal.\n";
int count = 0;
std::string guess;
while(animal.compare(std::toupper(guess)) != 0 && count < limit)
{
std::cout << "Can you guess what animal I am thinking of?: \n";
std::cin >> guess;
count++;
if(animal.compare(std::toupper(guess)) != 0)
{
std::cout << "\nHmm, nope. That's not the animal I'm thinking of.\n";
if(count > 2)
{
std::cout << "I'll give you a hint. It lives in water.\n";
}
}
}
}//End nested while loop
if(count >= limit)
{
std::cout << "\nI'm sorry, but you are out of guesses.\n";
}
else
{
std::cout << "\n*** Good job! You guessed the correct animal! ***\n";
std::cout << "\t\t><)))º> ❤ <º)))><\t\t\n";
}
char choose = 'Y' ;
std::cout << "Would you like to try again?(y/n): ";
std::cin >> choose;
if(std::toupper(choose) == 'N') break;
} while(true);
return 0;
}

Ask name, if wrong ask again, if right, keep going ( Not working ) C++

That's my code. What i'm trying to do here is a code that Asks for a name ( like a pass ) if the name is wrong, then the program says those 3 error messages and asks the name again, until one of the 2 white-listed names is given, then just keep going with the code.
int main(void)
{
setlocale(LC_ALL, "Portuguese");
string Name = "";
cout << "Whats your name dude ?" << endl;
cin >> Name;
if (Name == "ighor" ||
Name == "indio")
{
cout << "Welcome friend =D" << endl;
system("pause");
system("cls");
}
else
{
do
{
cout << "Sorry, wrong name =[" << endl;
system("pause");
system("cls");
cout << "I'll give you another chance =]" << endl;
system("pause");
system("cls");
cout << "Write your name again" << endl;
cin >> Name;
if (Name == "ighor" ||
Name == "indio")
{
continue;
}
} while (Name != "ighor" ||
Name != "indio");
}
cout << "Whats up" << Name << endl;
system("pause");
system("cls");
return 0;
}
My tests with this code gave me this :
If i put a white-listed name ( indio or ighor ) i get the massage of correct name
"Welcome friend =]".
If i put a wrong name, i get the massage of wrong name, nice, then i'm asked to enter the name again, i put one of the white-listed names and it keeps saying that it's the wrong name, wrong names also show wrong name message.
The logic in the do-while loop is flawed. Instead of
continue;
you need
break;
continue; continues with the next iteration of the loop. break; breaks the loop.
Also, the while statement logic incorrect. You need to use:
while (Name != "ighor" && Name != "indio");
^^^ not ||
Having said that, you only need one of the checks, not both.
You can use:
do
{
...
if (Name == "ighor" || Name == "indio")
{
break;
}
} while (true);
or
do
{
...
} while (Name != "ighor" && Name != "indio");
Try this:
int main() {
string name;
cout << "Whats your name dude ?" << endl;
cin >> name;
while (!(name == "ighor" || name == "indio")) {
cout << "Sorry, wrong name =[" << endl;
system("pause");
system("cls");
cout << "I'll give you another chance =]" << endl;
system("pause");
system("cls");
cout << "Write your name again" << endl;
cin >> name;
}
cout << "Whats up " << name << endl;
system("pause");
system("cls");
return 0;
}
it's shorted, cleaner, more expressive and it works too..
In your code:
Your condition was while (Name != "ighor" || Name != "indio"); which means if any of this two conditions is true then the Loop will continue it's work.If your input is "indio" then the first condition became true.
In my code:
while (Name != "ighor" && Name != "indio");which means this two condition must be true if one of them became false then the loop will stop it's work. Now, if your input is "indio" this condition became false and your loop will stop.
To know more about continue and break statement read this and this.
Try This:
int main(void)
{
setlocale(LC_ALL, "Portuguese");
string Name = "";
cout << "Whats your name dude ?" << endl;
cin >> Name;
if (Name == "ighor" ||
Name == "indio")
{
cout << "Welcome friend =D" << endl;
system("pause");
system("cls");
}
else
{
do
{
cout << "Sorry, wrong name =[" << endl;
system("pause");
system("cls");
cout << "I'll give you another chance =]" << endl;
//system("pause");
system("cls");
cout << "Write your name again" << endl;
cin >> Name;
if (Name == "ighor" ||
Name == "indio")
{
continue;
}
} while (Name != "ighor" &&
Name != "indio");
}
cout << "Whats up" << Name << endl;
system("pause");
system("cls");
return 0;
}
Thanks for all the answers i did changed
continue;
for
`break;`
and it worked perfect =)
But as the code was too confusing i may study a bit the other tips you guys gave me so i can make it cleaner =D
I just have another doubt with this piece of code
cin >> RPI;
if (RPI == "Sim"||RPI == "sim"||RPI == "vou"||RPI == "Vou")
What i wanted here was to "check" the answer and make something if i was "Sim" or "Vou" which(means "Yes" and "i will", but anyway)
I think that i can use what you guys told me about the "II" replacement for "&&" so it makes the condition correctly.
If there was a way or a command, so it don't differentiate Capital and lowercase just for this answer, so didn't i need to put both ways that the person can write would also help.
Thats just a learning code, only for studding propose
It was the first time i posted and really surprised, those lot of answers and it was too fast, thanks you all for the support.
You guys rule.
Good codding.
Please indent your code correctly.
Try replacing
continue;
by
break;
The continue statement goes through the loop again, what you want to do is exit it. Let me know if it works, as I am not able to test right now.

How do I break out of the for loop inside an inner while loop

For this loop, I need to be able to enter names into an array that has to be 100 elements long, and exit the array to read the names back once Q or q is entered, or the end of the array is reached. When I use this code, the program goes back to the beginning of the while loop without breaking the for loop.
for (int i = 0; i < 100; i++)
{
while (true)
{
cout << "Enter Player Name (Q to quit): ";
getline(cin,playerName[i]);
if (playerName[i] == "Q" || playerName[i] == "q")
break;
cout << "Enter score for " << playerName[i] << ": "<< endl << endl;
}
}
According to your description, it seems like the while (true) is completely redundant!!!
So you should simply do:
int i;
for (i = 0; i < 100; i++)
{
cout << "Enter Player Name (Q to quit): ";
getline(cin,playerName[i]);
if (playerName[i] == "Q" || playerName[i] == "q")
break;
cout << "Enter score for " << playerName[i] << ": "<< endl << endl;
}
At this point, you can use i in order to tell how many names have been entered by the user.
This is one of the rare circumstances where a judicious goto may be the best available option.
for (...)
{
while (...)
{
if (...)
goto exit_loop;
}
}
exit_loop:;
Some languages let you put a label on the for and use it in break, but C and C++ are not among them. It can also make sense to extract the entire loop nest to its own function, allowing you to use return to exit both loops, but this may not work in context.
I personally think that this use of goto is easier to understand than a boolean + if in the outer loop, as suggested in other answers, but reasonable people can disagree about that.
If I'm reading your question correctly, then you don't need the while loop. Without that while loop, break will exit the for loop, then you can enter a separate for loop (from 1 to 100) to print the contents of the array.
If the user enters less than 100 names at any point, then the second for loop will go from 1 to i, and output each array entry along the way.
I'm answering the title - wrap both loops in a function:
void foo()
{
for (;;)
while (true)
if (/* something */)
return;
}
I otherwise agree with barak manos, you don't even need two loops.
Add a boolean variable to tell you if the inner loop has broken:
bool broken = false;
for (int i = 0; i < 100; i++)
{
while (true)
{
cout << "Enter Player Name (Q to quit): ";
getline(cin,playerName[i]);
if (playerName[i] == "Q" || playerName[i] == "q") {
broken = true;
break;
}
}
cout << "Enter score for " << playerName[i] << ": "<< endl << endl;
}
if (broken) {
break;
}
}
use a boolean variable to state that you breaked from the inner loop and then check it and break from the outer loop if needed.
Try the following
bool done = false;
int i = 0;
for ( ; i < 100 && !done; i++ )
{
cout << "Enter Player Name (Q to quit): ";
getline(cin,playerName[i]);
if ( !( done = playerName[i] == "Q" || playerName[i] == "q" ) )
{
cout << "Enter score for " << playerName[i] << ": "<< endl << endl;
// some code for entering the score
}
}
Take into account that you need to keep variable i that to know how many players were entered. So I defined i outside the loop.

CTRL+Z makes program loop infinitely in C++

Ok I have a problem here. I am making a slide puzzle game. The player is asked which piece he wants to move until the puzzle is solved. If the player wants to exit before, typing Q or q and pressing enter will do it. The program works just fine. BUT I am having one problem: if I insert CTRL+Z, the program will loop unexpectedly...
This is the piece of code that matters:
// analyzes user input
if (piece_to_move_string == "q" ||
piece_to_move_string == "Q")
{
cout << endl << "You chose to quit." << endl;
pressanykey();
break;
}
else
{
piece_to_move = atoi(piece_to_move_string.c_str());
if (1 <= piece_to_move && piece_to_move <= pow(puzzle_size,puzzle_size))
{
game_board = move_piece (game_board, piece_to_move);
}
else
{
cout << "Not possible.";
}
}
EDIT: but still doesn't work..
// analyzes user input
if (piece_to_move_string == "q" ||
piece_to_move_string == "Q")
{
cout << endl << "You chose to quit." << endl;
pressanykey();
break;
}
else if (cin.eof())
{
//do nothing
}
else
{
piece_to_move = atoi(piece_to_move_string.c_str());
if (1 <= piece_to_move && piece_to_move <= pow(puzzle_size,puzzle_size))
{
game_board = move_piece (game_board, piece_to_move);
}
else
{
cout << "Not possible.";
}
}
Ctrl+Z means "end of file" (assuming you're on Windows) so once the user hits that, your cin is in an unreadable state. Check for cin.eof():
if (cin.eof() || piece_to_move_string == "q" ||
piece_to_move_string == "Q")
{
cout << endl << "You chose to quit." << endl;
}