Why does my program terminate when it should continue? - c++

#include <iostream>
#include <ctime>
using namespace std;
int main() {
int answer;
string question;
string play = "";
srand(time(NULL));
cout << "What question would you like to ask the Magic 8 ball?: \n";
cout << "\n";
cin >> question;
answer = rand () % 8 + 1;
if (answer == 1) {
cout << "The answer is: It is certain\n";
} else if (answer == 2) {
cout << "The answer is: It is decidely so\n";
} else if (answer == 3) {
cout << "The answer is: Most likely\n";
} else if (answer == 4) {
cout << "The answer is: Signs point to yes\n";
} else if (answer == 5) {
cout << "The answer is: Ask again later\n";
} else if (answer == 6) {
cout << "The answer is: Don't count on it\n";
} else if (answer == 7) {
cout << "The answer is: My sources say no\n";
} else {
cout << "The answer is: Reply hazy, try again\n";
}
cout << "Would you like to play again?(y/n): ";
cin >> play;
if (play == "yes" || play == "y") {
cin >> question;
} else if (play == "no" || play == "n") {
cout << "Thank you for playing with the Magic 8 Ball";
}
return 0;
}
It stops the program after it gives my answer, not letting the user answer if they want to play again or not. Please help me, I've been stuck on this for a while now and don't know what to do.

You have to add
getline(cin, question);
If you don’t,
cin >> question;
won’t be able to read more than one word.

you did most of the work you just have to make a loob like so
#include <iostream>
#include <ctime>
using namespace std;
int main() {
int answer;
string question;
string play = "";
srand(time(NULL));
while(play!="no"&&play!="n")
{
play = "";
cout << "What question would you like to ask the Magic 8 ball?: \n";
cout << "\n";
cin >> question;
answer = rand () % 8 + 1;
if (answer == 1) {
cout << "The answer is: It is certain\n";
} else if (answer == 2) {
cout << "The answer is: It is decidely so\n";
} else if (answer == 3) {
cout << "The answer is: Most likely\n";
} else if (answer == 4) {
cout << "The answer is: Signs point to yes\n";
} else if (answer == 5) {
cout << "The answer is: Ask again later\n";
} else if (answer == 6) {
cout << "The answer is: Don't count on it\n";
} else if (answer == 7) {
cout << "The answer is: My sources say no\n";
} else {
cout << "The answer is: Reply hazy, try again\n";
}
cout << "Would you like to play again?(y/n): ";
while(play != "no" && play != "n"&& play != "y" && play != "yes")
{cin >> play;
if (play == "no" || play == "n") {
cout << "Thank you for playing with the Magic 8 Ball";
} else if (play != "no" && play != "n"&& play != "y" && play != "yes") {
cout<<"you enter an unknown value, try agein"<<endl;
}
}
}
return 0;
}
i declare (string play) then i reassign it so it could not save the y/n answer from round to round cuz that would break the program and i add a loob down the code that will get you y/n answer more effective

Related

How to repeat input command if user input is invalid with a string variable - C++

So I have very little coding experience and the code I wrote has this problem of asking the user to input again if correctly choosing "yes" the first time. It works correctly if the user inputs "no" or if the user writes an invalid option, the next set of questions would work. I haven't found any examples dealing with string variables without using arrays. Thanks -
P.S. I know its crappy form but I'm just trying to get it to work.
#include<string>
#include<iostream>
using namespace std;
int main() {
string choice;
cout<<"Do you choose to go fight in the war??\n\n";
cout << "choose yes or no\n";
cin >> choice;
while(choice != "yes" || choice != "no")
{
cout << "pls enter again\n";
cin >> choice;
if(choice == "no")
{
cout << "you live";
break;
}
else(choice == "yes");
{
cout << "you die";
break;
}
}
}
Instead of else you need else if:
else if (choice == "yes") {
cout << "you die";
break;
}
One way is to use an infinite loop to handle the input. If a valid input is given, break the loop.
using namespace std;
int main()
{
string choice;
cout << "Do you choose to go fight in the war??\n\n";
cout << "choose yes or no\n";
while (true) {
cin >> choice;
if (choice == "no") {
cout << "you live";
break;
}
else if (choice == "yes")
{
cout << "you die";
break;
}
else {
cout << "pls enter again\n";
}
}
return 0;
}
When I started learning coding, I faced the same logic problems like what you are struggling at the moment. I just think that you are having problems with syntax and coding logic. Hope that my code can somehow help!
#include <iostream>
#include <string>
using namespace std;
int main() {
string choice;
do {
cout << "Do you choose to go fight in the war??\n";
cout << "Choose yes or no\n";
cin >> choice;
if (choice == "no") {
cout << "you live\n";
break;
} else if (choice == "yes") {
cout << "you die\n";
break;
}
} while (choice != "yes" && choice != "no");
return 0;
}
Use do- while loop for string input and after the loop apply conditions
#include<iostream>
using namespace std;
main()
{
String choice;
cout << "Do you choose to go fight in the war??\n\n";
cout << "choose yes or no\n";
do
{
cin >> choice;
If(choice != "yes" || choice != "no")
Cout<<"please enter again";
}
while (choice != "yes" || choice != "no");
If (choice == "no")
{
cout << "you live";
}
else
{
cout << "you die";
}
}

Can't figure out how to give user all the options for starting, stopping, and restarting program?

Ok so I am trying to build this random number teller which basically tells the users whether the number they input is less than, greater than, or equal to 50 and also give them the options to start, stop, and restart the "random number teller" Here is the code:
#include <iostream>
using namespace std;
main() {
cin >> boolalpha;
int invalid_answer {0};
const int const_num {50};
int random_num {};
char answer {};
int keep_going {};
while (keep_going == 0) {
while (invalid_answer == 0) {
//=======================================================================================================================================
cout << "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " << endl;
cin >> random_num;
if (random_num > const_num) {
cout << random_num << " is greater than " << const_num;
}
else if (random_num == const_num) {
cout << random_num << " is the same as " << const_num << endl;
}
else {
cout << random_num << " is less than " << const_num << endl;
}
cout << "Want to try again? Type \"Y\" or \"N\"";
cin >> answer;
//=======================================================================================================================================
if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}
//=======================================================================================================================================
while(answer == 'Y') {
cout << "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " << endl;
cin >> random_num;
if (random_num > const_num) {
cout << random_num << " is greater than " << const_num;
}
else if (random_num == const_num) {
cout << random_num << " is the same as " << const_num << endl;
}
else {
cout << random_num << " is less than " << const_num << endl;
}
cout << "\nWant to try again? Type \"Y\" or \"N\"";
cin >> answer;
}
//=======================================================================================================================================
if (answer != 'Y' || answer != 'N') {
invalid_answer = 1;
}
//=======================================================================================================================================
while (invalid_answer == 1) {
cout << "I'm sorry what? Please note that answers are case sensitive. Answer again: ";
cin >> answer;
if (answer == 'Y') {
invalid_answer = 0;
}
else if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}
}
}
}
}
Whenever I say "N" for No I don't want to redo the random number checker, it doesn't change keep_going to 1 it just moves on to one of the other if or while statements below it. So when you input "N" it just outputs either "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " or "I'm sorry what? Please note that answers are case sensitive. Answer again: "
The problem is with this bit of code:
if (answer != 'Y' || answer != 'N') {
invalid_answer = 1;
}
When answer is 'N', answer != 'Y' is true and invalid_answer is set to 1 (because of short-circuit evaluation the rhs of the logical OR is not even evaluated - see quote below).
So the execution will enter the while
while (invalid_answer == 1)
and will print the statements.
You can correct this by:
if (answer == 'Y' || answer == 'N') { //if input is either 'Y' or 'N'
invalid_answer = 0;
}
else { //for all other inputs
invalid_answer = 1;
}
Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands
Also note that main should have the type int.
I figured it out right after I posted the question haha, basically the answer above was correct so I had to split that if statement into 2 others, in which I added an else statement to each also that said invalid_answer = 0; to make sure. But then after the user's second time using the program, if they wanted to quit it wouldn't let them and would just restart it again. I solved that by adding
if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}`
to the bottom of the while(answer == 'Y') loop.

How to handle invalid inputs while displaying Game menus?

#include <iostream>
#include <string>
using namespace std;
int main() { //Program starts
cout << "-------------------------------" << endl;
cout << "Welcome to Ninjas vs. Samurais!" << endl; //The intro
cout << "-------------------------------" << endl;
string newAdventure;
string chosenKind;
cout << "Hello, new solder! Are you ready for your adventure to begin, yes or no?\n"; //Asks you if you are ready
cin >> newAdventure;//Takes in if you are ready or not
if (newAdventure == "yes" || newAdventure == "Yes" || newAdventure == "Yes!") { //Asks if they are ready
cout << "Great!\n" << endl;
}
else if (newAdventure == "no" || newAdventure == "No" || newAdventure == "No!") { //Asks if they are ready
cout << "Too bad!\n" << endl;
}
else {
cout << "Please type a yes or no answer!\n";
}
system("PAUSE");
return 0;
}
If the user didn't input a valid answer, how could I make them restart the question? Would I have to use a loop? If so, how would I do that?
Yes you would have to use a loop. Something like:
while(cin >> newAdventure)//Takes in if you are ready or not
{
if (newAdventure == "yes" || newAdventure == "Yes" || newAdventure == "Yes!") { //Asks if they are ready
cout << "Great!\n" << endl;
break;
}
else if (newAdventure == "no" || newAdventure == "No" || newAdventure == "No!") { //Asks if they are ready
cout << "Too bad!\n" << endl;
break;
}
else {
cout << "Please type a yes or no answer!\n";
}
}
The break keyword will exit the loop once your answer is valid, otherwise, it keeps going.
You can add a condition like this:
while(true)
{
cout << "Hello, new solder! Are you ready for your adventure to begin, yes or no?\n"; //Asks you if you are ready
cin >> newAdventure;//Takes in if you are ready or not
if (newAdventure == "yes" || newAdventure == "Yes" || newAdventure == "Yes!") { //Asks if they are ready
cout << "Great!\n" << endl;
break;
}
else if (newAdventure == "no" || newAdventure == "No" || newAdventure == "No!") { //Asks if they are ready
cout << "Too bad!\n" << endl;
break;
}
else {
cout << "Please type a yes or no answer!\n";
}
}

I Can't Figure Out Why This Loop Is Malfunctioning

So I just can't figure out what's wrong with my code. When I process a purchase, after I enter the amount of yogurt and am told to go enjoy it, I immediately after get the error message I made for if people don't input P or S, then right afterwards it goes back to normal like it is when you first enter the program, could anybody tell me why this is? Thank you!
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string userCommand;
int creditCount = 0;
int userInput;
while (creditCount >= 0)
{
cout << "--------Menu--------\n" << "P (Process Purchase)\n" << "S (Shutdown System)\n"
<< "--------Menu--------\n" << "Your Choice: ";
getline(cin, userCommand);
if (userCommand[0] == 'P' || userCommand[0] == 'p')
{
if (creditCount >= 10)
{
cout << "You qualify for a free yogurt, would you like to use ten of your credits (Yes or No)?";
getline(cin, userCommand);
if (userCommand[0] == 'Y' || userCommand[0] == 'y')
{
creditCount = creditCount - 10;
cout << "You just used 10 credits and now have " << creditCount << " left.\n"
<< "Enjoy your free yogurt!";
}
else if (userCommand[0] == 'N' || userCommand[0] == 'n')
{
cout << "How many yogurts would you like to buy? ";
cin >> userInput;
if (userInput > 0)
{
creditCount = creditCount + userInput;
cout << "You just earned " << userInput << " stamps. You now have " << creditCount
<< " credits! Enjoy your yogurt!";
}
else
{
cout << "Invalid input, please try processing your purchase again and enter a positive "
<< "integer.";
}
}
else
{
cout << "*Error, please try processing your purchase again and enter either Yes or No*\n\n";
}
}
else if (creditCount < 10)
{
cout << "How many yogurts would you like to buy? ";
cin >> userInput;
if (userInput > 0)
{
creditCount = creditCount + userInput;
cout << "You just earned " << userInput << " stamps. You now have " << creditCount
<< " credits! Enjoy your yogurt!\n\n";
}
else
{
cout << "Invalid input, please try processing your purchase again and enter a positive "
<< "integer.";
}
}
}
else if (userCommand[0] == 'S' || userCommand[0] == 's')
{
cout << "*Shutting down system*\n";
return 0;
}
else
{
cout << "*Error, please enter either P (for Process Purchase) or S (for Shutdown System)*\n\n";
}
}
}
#acid1789 has pointed out correctly the error is due to the empty line after getline. From your code what i can make out is you are using an infinite loop here
while(creditCount >= 0){...}
since creditCount is never going to be less than 0 instead of this you can use
while (true){...}
its just better programming practice.
And to correct your program you can just use
cin >> userCommand;
instead of
getline(cin, userCommand);
Hope it helps.
Edit:- Sorry Python habits..
The issue here is that getline is returning an empty line.
So after your first time through the loop, it goes back to the top to read another line. Gets an empty line, which triggers the error case.
You could fix this by testing for an empty line after getline.

Converting Integers to Strings and If.. Else Boolean Functions C++

I am working on this assignment that requires me to create a game of rock, paper scissors for my programming class. I have ran into a couple issues that I am not fully educated about as I am still learning the basics of this language. My professor wants me to take in the users choice and the computers choice and then change it from an int to a string and print it out as "You chose: Rock" instead of "You chose: 1" which is what it is doing now. This part would be in the getComputerChoice() and getPlayerChoice() functions. Another issue I am having trouble with is my professor wants us to check if it was a tie or if the player won and I am trying to put these functions in an If else statement but I am not exactly sure what the proper way to declare the function in the else statement is. (This is commented out in the else part of the if statement in main all the way at the bottom)
My code is as follows:
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
using namespace std;
int getComputerChoice();
int getPlayerChoice();
bool isTie(int, int);
bool isPlayerWinner(int, int);
int getComputerChoice()
{
int comp;
string cpChoice;
comp = rand() % 3 + 1;
if (comp == 1)
{
cpChoice = "Rock";
}
else if (comp == 2)
{
cpChoice = "Paper";
}
else if (comp == 3)
{
cpChoice = "Scissors";
}
return comp;
}
int getPlayerChoice()
{
int userChoice;
string strChoice;
cout << "Rock, Paper, or Scissors?\n";
cout << "1) Rock\n";
cout << "2) Paper\n";
cout << "3) Scissors\n";
cout << "Please enter your choice : \n";
cin >> userChoice;
cout << '\n';
while(userChoice < 1 || userChoice > 3)
{
cout << "Invalid Selection\n";
cout << "Re-enter a number between 1 and 3\n";
cin >> userChoice;
}
if (userChoice == 1)
{
strChoice = "Rock";
}
else if (userChoice == 2)
{
strChoice = "Paper";
}
else if (userChoice == 3)
{
strChoice = "Scissors";
}
return userChoice;
}
bool isTie(string userChoice, string comp)
{
if (userChoice != comp)
return false;
else
return true;
}
bool isPlayerWinner(int userChoice, int comp)
{
if ((comp == 1 && userChoice == 2) || (comp == 3 && userChoice == 1) || (comp == 2 && userChoice == 3))
return true;
else
return false;
}
int main()
{
char selection;
int computerChoice;
int userChoice1;
string Rock;
string Paper;
string Scissors;
srand ((unsigned int)time(NULL));
do
{
cout << '\n';
cout << "ROCK PAPER SCISSORS MENU\n";
cout << "-------------------------\n";
cout << "p) Play Game\n";
cout << "q) Quit\n";
cout << "Please enter your choice : \n";
cin >> selection;
cout << '\n';
cout << '\n';
// cin >> selection;
if (selection == 'p' || selection == 'P')
{
computerChoice = getComputerChoice();
//string computerChoice = to_string(comp);
userChoice1 = getPlayerChoice();
//string userChoice1 = to_string(userChoice);
cout << "You chose: " << userChoice1 << '\n';
cout << "The computer chose: " << computerChoice << '\n';
if (isTie(computerChoice, userChoice1)== true)
{
cout << "You choose: " << userChoice1;
cout << "The computer chose: " << computerChoice;
cout << "It's a TIE!";
}
else //(isPlayerWinner(computerChoice, userChoice1));
{
cout << "You choose: " << userChoice1;
cout << "The computer chose: " << computerChoice;
cout << "You WIN!";
}
}
//else if (selection != 'p' || selection != 'q')
//{
// cout << "Invalid Selection. Try Again.\n";
// cout << '\n';
// cin >> selection;
//}
else if (selection == 'q' || selection == 'Q')
{
cout << "You have chosen to quit the program. Thank you for using the program!\n";
}
else if (selection != 'p' || selection != 'q')
{
cout << "Invalid Selection. Try Again.\n";
cout << '\n';
}
}while (selection != 'q');
}
ANOTHER NOTE: my professor doesn't want any void functions and doesn't want any global variables.
She told me that my isTie function was fine but didn't mention anything about the isPlayerWinner function. I believe it is fine and has no issues, I am just not sure how to declare it in the main if else statement. Any help would be appreciated and if you guys have any questions or need more info please let me know. Thanks in advance.
You pretty much have everything right.
Your getPlayerChoice() and getComputerChoice() functions right now are both returning an int that stand for the players choice. You calculate the name for that choice in those functions, but dont do anything with the actual string representing the choice. You either need to return the choice string, or make a function that takes in an int and returns name associated with that choice:
string getChoiceName(int choice)
{
string strChoice;
if (choice== 1)
{
strChoice = "Rock";
}
else if (choice== 2)
{
strChoice = "Paper";
}
else if (choice== 3)
{
strChoice = "Scissors";
}
return strChoice;
}
I prefer the method, as it make it easier to calculate the result of the match if you have the ints. There are a lot of other routes you could take, like making an enum representing choices - even the function I gave you here isn't great, but it should get you to a working state.