how to add loop in c++ - c++

Could someone help me add a loop to my program?
Here's the code:
cout << "What do you do?" "\n";
cout << "\n";
cout << "(Press Enter...)";
cin.ignore();
cout << "\n";
cout << "Stay in bed?" "\n";
cout << "Go to the bathroom?" "\n";
cout << "Go downstairs?" "\n";
cout << "\n";
string answer;
getline(cin, answer);
if (answer == "stay in bed", "Stay in bed")
{
cout << "You lay there, motionless. Silent.";
}
else if (answer == "go to the bathroom", "Go to the bathroom")
{
cout << "You get up and walk across the hall to the bathroom";
}
else if (answer == "go downstairs", "Go downstairs")
{
cout << "You get up and walk downstairs to the kitchen.";
}
else
{
cout << "That is not a valid answer...";
}
cin.ignore();
How should I add a loop to where when user enters something falling under the condition of "else", the loop returns to ask "What do you do?"

There's more than one way to do what you want to do (or what I think you want to do). One way is to put the whole thing inside an endless loop and use break to get out:
while(1)
{
cout << "What do you do?\n";
getline(cin, answer);
if (answer == "stay in bed")
{
cout << "You lay there, motionless. Silent.";
break;
}
else if (answer == "go to the bathroom")
{
cout << "You get up and walk across the hall to the bathroom";
break;
}
}

bool repeatInput = false;
do
{
cout << "What do you do?" "\n";
cout << "\n";
cout << "(Press Enter...)";
cin.ignore();
cout << "\n";
cout << "Stay in bed?" "\n";
cout << "Go to the bathroom?" "\n";
cout << "Go downstairs?" "\n";
cout << "\n";
repeatInput = false;
getline(cin, answer);
if (answer == "stay in bed" || answer == "Stay in bed")
{
cout << "You lay there, motionless. Silent.";
}
else if (answer == "go to the bathroom" || answer == "Go to the bathroom")
{
cout << "You get up and walk across the hall to the bathroom";
}
else if (answer == "go downstairs" || answer == "Go downstairs")
{
cout << "You get up and walk downstairs to the kitchen.";
}
else
{
cout << "That is not a valid answer...";
repeatInput = true;
}
cin.ignore();
}while(repeatInput == true);

using while you can add a loop in your program
#include <iostream>
using namespace std;
int main()
{
while (true) {
cout << "What do you do?" "\n";
cout << "\n";
cout << "(Press Enter...)";
cout << "\n";
cout << "Stay in bed?" "\n";
cout << "Go to the bathroom?" "\n";
cout << "Go downstairs?" "\n";
cout << "\n";
string answer;
getline(cin, answer);
if (answer == "stay in bed", "Stay in bed")
{
cout << "You lay there, motionless. Silent." << endl;
}
else if (answer == "go to the bathroom", "Go to the bathroom")
{
cout << "You get up and walk across the hall to the bathroom" << endl;
}
else if (answer == "go downstairs", "Go downstairs")
{
cout << "You get up and walk downstairs to the kitchen." << endl;
}
else
{
cout << "That is not a valid answer..." << endl;
}
cout << endl;
}
return 0;
}
this code while(true) if the condition is true or 1 the code inside the brackets will execute and if the condition is false or 0 the code will exit the loop

this answer spare of putting break in every else-if function. I used "continue" in hope you will explore c++ language and learn more!
bool check_if_true=true;
while(check_if_true){
cout << "What do you do?" "\n";
cout << "\n";
cout << "(Press Enter...)";
cin.ignore();
cout << "\n";
cout << "Stay in bed?" "\n";
cout << "Go to the bathroom?" "\n";
cout << "Go downstairs?" "\n";
cout << "\n";
string answer;
getline(cin, answer);
if (answer == "stay in bed", "Stay in bed")
{
cout << "You lay there, motionless. Silent.";
}
else if (answer == "go to the bathroom", "Go to the bathroom")
{
cout << "You get up and walk across the hall to the bathroom";
}
else if (answer == "go downstairs", "Go downstairs")
{
cout << "You get up and walk downstairs to the kitchen.";
}
else
{
cout << "That is not a valid answer...";
continue;//return to the start of the while loop
}
cin.ignore();
check_if_true=false;
}

You should use integer identifiers when giving a user options.
#include <iostream>
using namespace std;
int main()
{
int id;
cout << "What do you wanna do?\n" << endl;
cout << "(0) Quit program" << endl;
cout << "(1) Stay in bed" << endl;
cout << "(2) Go to the bathroom" << endl;
cout << "(3) Go downstairs\n" << endl;
while (id != 0)
{
cout << "Choose your option: ";
cin >> id;
switch (id)
{
case 1:
cout << "You lay there, motionless. Silent." << endl;
break;
case 2:
cout << "You get up and walk across the hall to the bathroom." << endl;
break;
case 3:
cout << "You get up and walk downstairs to the kitchen." << endl;
break;
case 0:
cout << "Exitting application!" << endl;
break;
default:
cout << "Error: Invalid option!" << endl;
break;
}
}
return 0;
}
The code is a lot cleaner and easily extensible. You should never have a user input strings when denoting options. The only exception is if you have an underlying program that scans the sentences and derives a course of action from 'keywords' found in the sentence. This is more algorithmic intensive and probably not what you're after, and assuming you are new to C++ I relate to my code in showing that this is the solution that's more practical in your situation. The code was tested, and runs fine.

Related

Getting loop to redisplay message c++

I am trying to get a program to display a menu with options, then given the user input, display a certain message. After it displays their message I want the loop to go back to displaying the message until they choose the quit option. How do I get the loop to return to displaying the menu after any choice of 1-3?
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int menu_choice;
cout << "Select a numerical option:" << endl << "=== menu ===" << endl << "1. Fox" << endl << "2. Bunny" << endl << "3. Sloth" << endl << "4. Quit" << endl;
cin >> menu_choice;
while (menu_choice >= 1 && menu_choice <= 4)
{
while (menu_choice == 1)
{
cout << "1 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 2)
{
cout << "2 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 3)
{
cout << "3 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 4)
{
cout << "4 work" << endl;
menu_choice = 0;
continue;
}
}
return 0;
}
Your code is displaying the menu only 1 time. If the user enters an invalid choice, you exit right away. If the user enters a valid choice, you do the chosen work, but then you exit rather than display the menu again. All of your while..continue loops are completely useless, they only run 1 time at most, setting the menu_choice to 0, which breaks your outer while loop so it runs only 1 time as well.
You need an outer loop that runs continuously, displaying the menu each time, until you are actually ready to exit.
You should also replace the useless while..continue loops with if/else blocks, or better a single switch block.
Try something more like this instead:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int menu_choice;
do
{
cout << "Select a numerical option:" << endl
<< "=== menu ===" << endl
<< "1. Fox" << endl
<< "2. Bunny" << endl
<< "3. Sloth" << endl
<< "4. Quit" << endl;
if (!(cin >> menu_choice))
{
menu_choice = 0;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
switch (menu_choice)
{
case 1:
cout << "1 work" << endl;
break;
case 2:
cout << "2 work" << endl;
break;
case 3:
cout << "3 work" << endl;
break;
case 4:
cout << "4 work" << endl;
break;
default:
cout << "Bad choice! Try again" << endl;
break;
}
}
while (menu_choice != 4);
return 0;
}
#Remy Lebeau was quicker posting and his answer is well written, but since I was done writing the code and you might benefit looking at different implementations I'm posting the code. I deliberately chose not to use switch since you might not have seen it before.
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
bool quit = false;
int menu_choice;
while(!quit) {
cout << "Select a numerical option:" << endl
<< "=== menu ===" << endl
<< "1. Fox" << endl
<< "2. Bunny" << endl
<< "3. Sloth" << endl
<< "4. Quit" << endl;
if(cin >> menu_choice) {
if(menu_choice == 1) {
cout << "1 work" << endl;
}
if(menu_choice == 2) {
cout << "2 work" << endl;
}
if(menu_choice == 3) {
cout << "3 work" << endl;
}
if(menu_choice == 4) {
cout << "Bye" << endl;
quit = true; // Set quit to true to stop the while loop
} else {
cout << "Invalid number" << endl;
}
} else {
cout << "Bad input" << endl;
cin.clear();
cin.ignore();
}
}
return 0;
}
Note that the cin.ignore and cin.clear are important and often confuse people new to this. Read this question for the details.

c++ - Text RPG - Checking For Valid Inputs With Functions

Good evening.
I am currently developing a text RPG. I've been trying to work on a function to vet all my inputs, so that a person would not be able to break my program (or have nothing happen) when they type a string outside of the "accepted" ones for my game. I have this so far, but it is automatically printing "That is not a valid input" for all three of my test cases, even if it is valid. The valid function still executes from the string on top of the "not valid input" prints...
Disclaimer: I have only been studying C++ for about a month, so I am sure the code for this is very procedural, and not in line with OOP. In my class, we have not covered objects/classes, or even vectors/arrays (I have learned these on my own). So my code may be very redundant...
I have included all of my code as to get a full understanding of my program.
My code is as follows:
#include <iostream>
#include <cmath>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <string>
using namespace std;
// This prints all commands used in-game upon input.
void userHelp(string action) {
if (action == "HELP") {
cout << endl;
cout << "Type 'look' to check your surroundings." << endl;
cout << "Type 'location' to print current area and map." << endl;
cout << "Type 'check [item]' to interact with items." << endl;
cout << "Type 'inventory' to check your inventory." << endl;
cout << "Type 'move [north, west, south, east]' to move." << endl;
cout << "Type 'talk [person type]' to begin conversation." << endl;
cout << "Type 'pick up [item]' to pick up items." << endl;
cout << endl;
}
}
void inputVetting(string action) {
while (action = true) {
if (action != "HELP" || action != "LOOK" || action != "LOCATION" || action != "PICK UP BRASS KEY") {
cout << endl;
cout << "That is not a valid input." << endl;
cout << endl;
}
if (action != "CHECK TABLE" || action != "INVENTORY" || action != "TALK GHOUL" || action != "PICK UP KEY") {
cout << endl;
cout << "That is not a valid input." << endl;
cout << endl;
}
if (action != "MOVE NORTH" || action != "MOVE SOUTH" || action != "MOVE EAST" || action != "MOVE WEST") {
cout << endl;
cout << "That is not a valid input." << endl;
cout << endl;
}
}
}
// This prints description lines for the player to check their surroundings of each room upon input.
// This makes it easy to add & change description lines for each room.
void look(string action, int currentRoom) {
if (action == "LOOK") {
if (currentRoom == 1) {
cout << endl;
cout << "There is a table and lamp in the room." << endl;
cout << "There is a ghoulish creature standing in the corner." << endl;
cout << "He seems friendly." << endl;
cout << "There is a door to the north." << endl;
cout << endl;
}
if (currentRoom == 2) {
cout << endl;
cout << "Description line 1." << endl;
cout << "Description line 2." << endl;
cout << "Description line 3." << endl;
cout << "Description line 4." << endl;
cout << endl;
}
}
}
// This prints current player area, and gives visual map of game zone upon input.
void location(string action, int currentRoom) {
if (action == "LOCATION") {
if (currentRoom == 1) {
cout << endl;
cout << "You are currently in room one." << endl;
cout << "|-----------------------------|" << endl;
cout << "| |" << endl;
cout << "| |" << endl;
cout << "| |" << endl;
cout << "| T E S T 1 |" << endl;
cout << "| |" << endl;
cout << "| |" << endl;
cout << "| |" << endl;
cout << "|-----------------------------|" << endl;
cout << endl;
}
if (currentRoom == 2) {
cout << endl;
cout << "You are currently in room two." << endl;
cout << "|-----------------------------|" << endl;
cout << "| |" << endl;
cout << "| |" << endl;
cout << "| |" << endl;
cout << "| T E S T 2 |" << endl;
cout << "| |" << endl;
cout << "| |" << endl;
cout << "| |" << endl;
cout << "|-----------------------------|" << endl;
cout << endl;
}
}
}
// This provides interactions with objects placed according to each area in the game zone upon input.
void checkItem(string action, int currentRoom) {
if (currentRoom == 1) {
if (action == "CHECK TABLE") {
cout << endl;
cout << "Description line A." << endl;
cout << "Description line B." << endl;
cout << "Do you want to open the drawer?" << endl;
cout << "(1) Yes\n(2) No" << endl;
cout << endl;
string choice;
cin >> choice;
boost::to_upper(choice);
if (choice == "1" || choice == "YES") {
cout << endl;
cout << "You open the drawer." << endl;
cout << "There is a brass key inside." << endl;
cout << endl;
} else if (choice == "2" || choice == "NO") {
cout << endl;
cout << "You leave the drawer alone." << endl;
cout << endl;
}
}
}
}
//This simple function allows user to pick up the key in the first game area.
void pickUpKey(string action, int currentRoom, vector<string>& inventory) {
if (currentRoom == 1) {
if (action == "PICK UP KEY" || action == "PICK UP BRASS KEY") {
cout << endl;
cout << "You have picked up the brass key." << endl;
cout << "It is now in your inventory." << endl;
cout << endl;
inventory.push_back("Brass Key");
}
}
}
// This prints description lines for the first game area.
void firstRoom() {
cout << endl;
cout << "You awake in a dark cabin-like room." << endl;
cout << "(Type 'help' for commands)" << endl;
}
//This prints description lines for the second game area.
void secondRoom() {
cout << "Description line 1." << endl;
cout << "Description line 2." << endl;
cout << "Description line 3." << endl;
cout << "Description line 4." << endl;
}
// This helps player move around the first area upon input.
// I've split up the movements into functions per room, for easier altering/flow
void movePlayerFirstRoom(string action, int& currentRoom, vector<string>& inventory) {
if (action == "MOVE NORTH" && currentRoom == 1) {
std::vector<string>::iterator it;
it = find(inventory.begin(), inventory.end(), "Brass Key");
if (it != inventory.end()) {
currentRoom = 2;
cout << endl;
} else {
cout << endl;
cout << "The door is locked!" << endl;
cout << endl;
}
}
if (action == "MOVE SOUTH" && currentRoom == 1) {
cout << endl;
cout << "You can't walk past a wall!" << endl;
cout << endl;
}
if (action == "MOVE EAST" && currentRoom == 1) {
cout << endl;
cout << "You can't walk past a wall!" << endl;
cout << endl;
}
if (action == "MOVE WEST" && currentRoom == 1) {
cout << endl;
cout << "You can't walk past a wall!" << endl;
cout << endl;
}
}
// This helps player move around the second area upon input.
void movePlayerSecondRoom(string action, int& currentRoom) {
if (action == "MOVE NORTH" && currentRoom == 2) {
cout << endl;
cout << "You can't walk past a wall!" << endl;
cout << endl;
}
if (action == "MOVE SOUTH" && currentRoom == 1) {
cout << endl;
cout << "Juub closed the door behind him." << endl;
cout << "You can no longer go that way." << endl;
cout << endl;
}
if (action == "MOVE EAST" && currentRoom == 1) {
cout << "You can't walk past a wall!" << endl;
cout << endl;
}
if (action == "MOVE WEST" && currentRoom == 1) {
cout << "You can't walk past a wall!" << endl;
cout << endl;
}
}
// This provides a for loop to display the items in player's inventory, used in checkInventory.
void listInventory(vector<string> inventory) {
for (auto i : inventory) {
cout << ":: " << i << endl;
}
}
// This prints out a player's inventory upon input.
void checkInventory(string action, vector<string>& inventory) {
if (action == "INVENTORY") {
cout << endl;
cout << "Your inventory contains: " << endl;
listInventory(inventory);
cout << endl;
}
}
// This provides basic mechanics for combat against enemies.
// void attackEnemy;
// This is the dialogues for NPC 1.
void npcOne(string action) {
if (action == "TALK GHOUL") {
string choice;
cout << endl;
cout << "Ah, hello." << endl;
cout << "I haven't seen anyone around here in a long time." << endl;
cout << "Name's Juub. I've been down here trying to find treasure." << endl;
cout << "Problem is, I haven't found anything..." << endl;
cout << "... but I have found a monster." << endl;
cout << "Actually, that's why I'm in this room." << endl;
cout << "A corrupted spirit chased me into here." << endl;
cout << "I was lucky enough to lock myself in, otherwise I'd surely be dead." << endl;
cout << "But... now, that you're here..." << endl;
cout << "Mind helping me out?" << endl;
cout << endl;
cout << "Do you want to help Juub kill the monster?" << endl;
cout << "(1) Yes\n(2) No" << endl;
cout << endl;
cin >> choice;
boost::to_upper(choice);
cout << endl;
if (choice == "1" || "YES") {
cout << "Excellent." << endl;
cout << "I wish I could be of help, but I got a bad arm." << endl;
cout << "Got shot in the Great War by a phaser rifle." << endl;
cout << "Come back with his essence, and I'll give you a reward." << endl;
cout << "... oh, yeah. The key to the door is somewhere in this room." << endl;
cout << endl;
} else if (choice == "2" || "NO") {
cout << "Eh, figures..." << endl;
cout << "Can never trust humanoids, anyway." << endl;
cout << endl;
}
}
}
// This is a small function to get the user's name, used in gameIntro.
void getName() {
cout << "Please enter your name." << endl;
cout << endl;
string name;
cin >> name;
cout << endl;
cout << "Welcome, " << name << ". Enjoy the game!" << endl;
}
// This is the introduction prompt of the game.
// This gives players the option to play or quit the game, then sets player's name.
void gameIntro() {
cout << endl;
cout << "==============================" << endl;
cout << "Welcome to *Love Pits*" << endl;
cout << "==============================" << endl;
cout << endl;
getName();
cout << endl;
cout << "..." << endl;
cout << "..." << endl;
cout << "..." << endl;
// cout << string(60, '\n'); <-- This is an attempt to try and clear screen, not sure if I want to do this.
}
int main() {
vector<string> inventory;
int currentRoom;
string action;
inventory.push_back("Rusted Dagger");
while (true) {
gameIntro();
currentRoom = 1;
firstRoom();
cout << endl;
// All possible actions/interactions within room one.
while (currentRoom == 1) {
if (currentRoom != 1) {
break;
}
getline(cin, action);
boost::to_upper(action);
//Provides all possible actions for player.
checkInventory(action, inventory);
checkItem(action, currentRoom);
userHelp(action);
look(action, currentRoom);
location(action, currentRoom);
movePlayerFirstRoom(action, currentRoom, inventory);
npcOne(action);
pickUpKey(action, currentRoom, inventory);
inputVetting(action);
}
secondRoom();
cout << endl;
// All possible actions/interactions in game area two.
while (currentRoom == 2) {
if (currentRoom != 2) {
break;
}
getline(cin, action);
boost::to_upper(action);
// Provides all possible actions for player.
checkInventory(action, inventory);
checkItem(action, currentRoom);
userHelp(action);
look(action, currentRoom);
movePlayerSecondRoom(action, currentRoom);
location(action, currentRoom);
}
}
}
Can anyone help me figure out why my vetting function isn't working? Or, if better, what are some things and places I can do them where I can vet the input properly, so the user can only type in commands that will work within the program, otherwise I print out something like "That is not a valid input"? Thanks for any help! I am just trying to improve as much as possible.
Check your logic. How we speak English does not translate into how we apply boolean logic to an if statement.
if (action != "HELP" || action != "LOOK" || action != "LOCATION" || action != "PICK UP BRASS KEY")
Let's say that you input "LOOK". Here is what that entire if breaks down to:
if (action != "HELP" || // true
action != "LOOK" || // false
action != "LOCATION" || // true
action != "PICK UP BRASS KEY") // true
Since you apply || (or) to all of those tests, all that is required is that one of those tests becomes true for the whole thing to be true. So that entire if becomes true, and thus enters the if error block.
The fix is to use && (and):
if (action != "HELP" && action != "LOOK" && action != "LOCATION" && action != "PICK UP BRASS KEY")
Now let's see how this goes if "LOOK" is entered:
if (action != "HELP" && // true
action != "LOOK" && // false
action != "LOCATION" && // true
action != "PICK UP BRASS KEY") // true
Now, if any of those conditions is false, then the whole if becomes false, thus does not enter the error block.
Compare now if "ABC" is entered:
if (action != "HELP" && // true
action != "LOOK" && // true
action != "LOCATION" && // true
action != "PICK UP BRASS KEY") // true
Thus "ABC" doesn't match any of the choices, thus the if becomes true and enters the error block.
A further point -- if you had more entries to check, having an endless if statement does not scale very well. Consider putting the words in a table and do a lookup, i.e. an unordered_set or similar, and just use find() to see if the entry is in the table.

How do I run part of my code until I break?

I need help with my code I will put it all in if anyone can clean it up so it looks nice but I will then highlight what I need help with.
#include <Windows.h>
#include <stdlib.h>
#include "stdafx.h"
#include <string>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
string ready;
system("#echo off");
system("cls");
cout << "ready to play? (y/n to play.): " << endl;
cin >> ready;
if (ready != "y")
do {
cout << "O.K. Goodbye!" << endl;
return 0;
} while (ready == "y");
cout << "OK!" << endl;
system("pause");
system("cls");
int number = 0;
int min = 1;
int max = 125;
int userinput;
srand(time(0));
number = rand() % (max - min + 1) + min;
int guesses_left = 10;
cout << "please try to guess a number between 1 and 125, you currently have: " << guesses_left << " guesses left" << endl;
cin >> userinput;
if (userinput > number){
cout << "Sorry your guess is too high, please guess again.";
cout << endl;
cout << "you now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput < number){
cout << "Soory, your guess is too low, please guess again." << endl;
cout << "You now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput == number){
cout << "congrats you won :)... Here have a prize as you won with: " << guesses_left << " guesses left." << endl << "no but seriously WELL DONE!!! :D";
system("cd C:\Program Files\Internet Explorer");
system("iexplore https://media.property118.com/wp-content/uploads/2013/12/Best-Property-Forum.jpg");
return 0;
}
return 0; }
The bit I am struggling with is this
cout << "please try to guess a number between 1 and 125, you currently have: " << guesses_left << " guesses left" << endl;
cin >> userinput;
if (userinput > number){
cout << "Sorry your guess is too high, please guess again.";
cout << endl;
cout << "you now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput < number){
cout << "Soory, your guess is too low, please guess again." << endl;
cout << "You now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput == number){
cout << "congrats you won :)... Here have a prize as you won with: " << guesses_left << " guesses left." << endl << "no but seriously WELL DONE!!! :D";
system("cd C:\Program Files\Internet Explorer");
system("iexplore https://media.property118.com/wp-content/uploads/2013/12/Best-Property-Forum.jpg");
return 0;
}
I am trying to loop this segment of code until I am bothered to add in you losing lives in the game. So if I get guess higher it should say it is higher and then loop back to give me another go. I have only started learning C++ yesterday and this is all mostly my code (some of it is adapted from other peoples posts like the srand and number = rand thing are other peoples)
I changed your "y/n" while loop to this :
cout << "ready to play? (y/n to play.): " << endl;
cin >> ready;
if (ready != "y")
{
cout << "O.K. Goodbye!" << endl;
return 0;
}
else
cout << "OK!" << endl;
I am also giving you a while version if you want to force the user to press either 'y' or 'n' to go further :
cout << "ready to play? (y/n to play.): " << endl;
cin >> ready;
while ( ready != 'y' && ready != 'n')
{
cout << "Only answer with 'y' or 'n' "<< endl;
cin >> ready;
}
and the game loop where user guesses to this :
int guesses_left = 10;
cout << "please try to guess a number between 1 and 125, you currently have: " << guesses_left << " guesses left" << endl;
while (guesses_left != 0)
{
cin >> userinput;
if (userinput > number){
cout << "Sorry your guess is too high, please guess again.";
cout << endl;
--guesses_left;
cout << "you now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput < number){
cout << "Soory, your guess is too low, please guess again." << endl;
--guesses_left;
cout << "You now have: " << guesses_left << " guesses left. Please choose again.";
}
else if (userinput == number){
cout << "congrats you won :)... Here have a prize as you won with: " << guesses_left << " guesses left." << endl << "no but seriously WELL DONE!!! :D";
system("cd C:\Program Files\Internet Explorer");
system("iexplore https://media.property118.com/wp-content/uploads/2013/12/Best-Property-Forum.jpg");
return 0;
}
}
cout << "You have used up all your guesses." << endl;
return 0;

C++ If, else if not reading else if. OR Find function incorrect? [duplicate]

This question already has answers here:
if statement not working right?
(5 answers)
Closed 6 years ago.
I can't quite figure this out. The program builds no problem. The issue is that no matter what the user input is, the if statement goes ahead and the program does not check the else if statement. I assume there's a larger structural problem in my script, but I'm not sure what it is.
It could be a problem with the find function. I'm still new to this function.
It could also be to do with how I'm nesting this new if-else-if statement within another if statement.
The problem comes towards the end of the code, in the final if-else-if. I'm pasting the whole thing in case it's a deeper issue elsewhere in the code. The previous if statement works fine. Here's the specific piece of code with the problem:
if (song.find(str2)){
cout << "Thank you! I, personally, love this song.\n";
cout << "I probably wouldn't listen to you if you asked me to turn it off.\n";
Sleep(20000);
}
else if (song.find(str3)){
cout << "It's not coming off, " << name <<"." << endl;
}
Thanks for any help. Much appreciated :)
Here's the full code:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int emotion;
void Sleep()
{
Sleep();
}
void loneliness()
{
cout << "Lonely. You must be strong, and loved, if you choose this feeling to explore.";
}
void inlove()
{
cout << "In love. You've been watching telenovelas again.";
}
void ambitious()
{
cout << "Ambitious. Steve Jobs Steve Jobs.";
}
void happy()
{
cout << "Happy. Is this a thing you can just feel?";
}
int main() {
string input;
string input2;
string name;
cout << "I'm bad." << endl;
cout << "My name's Raab." << endl;
cout << "Your name?" << endl;
getline(cin, name);
cout << "Tell me in one word what emotion you're feeling right now." << endl;
getline(cin, input);
cout << "Haha. " << input << "?" << " " << "Alright. I can work with that." << endl;
cout << "..." << endl;
cout << "Okay, I'm going to give you a choice." << endl;
cout << "You can trade that emotion for one other, if you'd like." << endl;
cout << "Would you like to do that?" << endl;
getline(cin, input2);
if (input2 == "Yes" && "yes") {
int emotion;
cout << "Nice one, bro.\n";
Sleep(350);
cout << "Here are your options!\n";
Sleep(300);
cout << "1. Lonely\n";
cout << "2. In love.\n";
cout << "3. Ambitious.\n";
cout << "4. Happy.\n";
cin >> emotion;
switch (emotion) {
case 1:
loneliness();
break;
case 2:
inlove();
break;
case 3:
ambitious();
break;
case 4:
happy();
break;
}
cin.get();
}
else if (input2 == "No" && "no")
{
std::string song;
std::string str2 ("like");
std::string str3 ("off");
cout << "Well" << endl;
Sleep(250);
PlaySound(TEXT("whip"), NULL, SND_ASYNC|SND_FILENAME);
cout << "." << endl;
Sleep(300);
PlaySound(TEXT("whip"), NULL, SND_ASYNC|SND_FILENAME);
cout << "." << endl;
Sleep(300);
PlaySound(TEXT("whip"), NULL, SND_ASYNC|SND_FILENAME);
cout << "." << endl;
Sleep(300);
PlaySound(TEXT("gravity"), NULL, SND_ASYNC|SND_FILENAME);
Sleep(2500);
cout << "Here we go. You like this song? Or do you want me to turn it off?\n";
Sleep(2000);
cout <<"Wait.\n";
Sleep(2000);
cout << "Don't tell me yet. I'm grooving.\n";
Sleep(7000);
cout << "Okay, tell me what to do, " << name << "." << endl;
getline(cin, song);
if (song.find(str2)){
cout << "Thank you! I, personally, love this song.\n";
cout << "I probably wouldn't listen to you if you asked me to turn it off.\n";
Sleep(20000);
}
else if (song.find(str3)){
cout << "It's not coming off, " << name <<"." << endl;
}
return 0;
}
return 0;
}
**EDIT:
I sort of fixed the issue.
I changed the above extract of code to this:
if (~song.find(str2))
{
cout << "Thank you! I, personally, love this song.\n";
cout << "I probably wouldn't listen to you if you asked me to turn it off.\n";
Sleep(20000);
}
else if (!~song.find(str2))
{
cout << "It's not coming off, " << name <<"." << endl;
Sleep(20000);
}
So it doesn't check for str3 anymore, but it does check if str2 is absent. This is progress, and fudges a solution, but it doesn't really give me a deeper understanding that I can bring forward with me so I would still appreciate answers :)
**
The line is incorrect :
if (input2 == "Yes" && "yes")
The && doesn't work that way. You have to perform the comparison with each value in the if statement. It should be:
if(input2 == "Yes" || input2 =="yes")
Likewise, the line
else if (input2 == "No" && "no")
should be:
if(input2 == "No" || input2 =="no")

How do i make a condition that will end the program, and prevent further cout statements?

I'm currently making a text-based game just for kicks, which gives the user three options to choose from. One of the options allows the user to continue, while the others end the game with a "GAME OVER" text. I thought that making an endGame() function would do the trick, but the terminal still outputs the rest of the cout statements. How can I make the endGame() function end the program?
(The program isn't finished yet, I still plan on adding a lot of features. I just can't continue until I solve this.)
Also, is there a way I can confirm that the user inputs either 1, 2, or 3 for each question and return "Enter 1, 2 or 3!" for wrong answers, without having to code it into each question?
#include <iostream>
#include <string>
using namespace std;
void endGame (void)
{
cout << "GAME OVER\n";
}
int main()
{
string userName;
//int choice1;
//int choice2;
//int choice3;
int event1;
int event2;
int event3;
int event4;
int event5;
cout << "What is your name, traveler?" << endl;
cin >> userName;
cout << "\nWelcome, " << userName << "." << endl;
cout << "I'm going to ask you a series of questions." << endl;
cout << "To cotinue your adventure, answer them by typing" << endl;
cout << "either 1, 2, or 3." << endl;
cout << "\nYou're walking down a long dirt road. You hear footsteps behind you," << endl;
cout << "but you're too afraid to look right now. A fork in the road lies infront of you." << endl;
cout << "\nWhat do you do?" << endl;
cout << "1 - Turn left, and run down the hill." << endl;
cout << "2 - Turn right, and run towards the abandoned house in the distance." << endl;
cout << "3 - Gain the courage to turn around and face whatever is behind you." << endl;
cin >> event1;
if(event1 == 1)
{
cout << "Unfortunatley, you trip over a branch, and fall to your death.\n" << endl;
endGame();
}
else if(event1 == 2)
{
cout << "You run towards the house, and escape the creature following you." << endl;
}
else if(event1 == 3)
{
cout << "You turn around, but before you can make out the features of the creature behind you, it kills you.\n" << endl;
endGame();
}
cout << "As you get closer to the house, you notice a light is on upstairs." << endl;
cout << "A small path leads to the back of the house.\n" << endl;
cout << "What do you do?" << endl;
cout << "1 - Knock on the door, and hope whoever is inside won't kill you." << endl;
cout << "2 - Enter the hoouse unanounced, and sneak upstairs." << endl;
cout << "3 - Follow the path to the back of the house." << endl;
cin >> event2;
if(event2 == 1)
{
cout << "A drunk, confused man answers the door, shotgun in hand." << endl;
cout << "You raise your hands in defense, but before you can explain yourself, he shoots." << endl;
endGame();
}
else if(event2 == 2)
{
cout << "You slowly open the door, and quietly sneak upstairs." << endl;
}
else if(event2 == 3)
{
cout << "You sneak around the house, and become face to face with a vicious gaurd dog." << endl;
cout << "Before you can give it a Scooby-Snac, it bits your throat, and kills you." << endl;
endGame();
}
cout << "You see three doorways, one leads to a dimly lit room, the second to a brightly lit room, and the third to a pitch black room." << endl;
cout << "\nWhat do you do?" << endl;
return 0;
}
I would suggest you use switch case for the conditions and a while loop for the enter 1,2,3 thing.. Something like
bool running=true;
while(running)
{
running = false;
switch(i)
{
case 1: stuff; break;
case 2: stuff; break;
case 3: stuff; break;
default: cout<<"enter 1,2,3"; running = true;
}
}
For the endgame thing make the endgame function lime this
void endgame()
{
cout<<"game over";
system("PAUSE");
exit(0);
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string userName;
//int choice1;
//int choice2;
//int choice3;
int event1;
int event2;
int event3;
int event4;
int event5;
int gameOver = 0;
cout << "What is your name, traveler?" << endl;
cin >> userName;
cout << "\nWelcome, " << userName << "." << endl;
cout << "I'm going to ask you a series of questions." << endl;
cout << "To cotinue your adventure, answer them by typing" << endl;
cout << "either 1, 2, or 3." << endl;
cout << "\nYou're walking down a long dirt road. You hear footsteps behind you," << endl;
cout << "but you're too afraid to look right now. A fork in the road lies infront of you." << endl;
cout << "\nWhat do you do?" << endl;
cout << "1 - Turn left, and run down the hill." << endl;
cout << "2 - Turn right, and run towards the abandoned house in the distance." << endl;
cout << "3 - Gain the courage to turn around and face whatever is behind you." << endl;
cin >> event1;
if(event1 == 1)
{
cout << "Unfortunatley, you trip over a branch, and fall to your death.\n" << endl;
gameOver = 1;
}
else if(event1 == 2)
{
cout << "You run towards the house, and escape the creature following you." << endl;
}
else if(event1 == 3)
{
cout << "You turn around, but before you can make out the features of the creature behind you, it kills you.\n" << endl;
gameOver = 1;
}
if (!gameOver)
{
cout << "As you get closer to the house, you notice a light is on upstairs." << endl;
cout << "A small path leads to the back of the house.\n" << endl;
cout << "What do you do?" << endl;
cout << "1 - Knock on the door, and hope whoever is inside won't kill you." << endl;
cout << "2 - Enter the hoouse unanounced, and sneak upstairs." << endl;
cout << "3 - Follow the path to the back of the house." << endl;
cin >> event2;
if(event2 == 1)
{
cout << "A drunk, confused man answers the door, shotgun in hand." << endl;
cout << "You raise your hands in defense, but before you can explain yourself, he shoots." << endl;
gameOver = 1;
}
else if(event2 == 2)
{
cout << "You slowly open the door, and quietly sneak upstairs." << endl;
}
else if(event2 == 3)
{
cout << "You sneak around the house, and become face to face with a vicious gaurd dog." << endl;
cout << "Before you can give it a Scooby-Snac, it bits your throat, and kills you." << endl;
gameOver = 1;
}
if (!gameOver)
{
cout << "You see three doorways, one leads to a dimly lit room, the second to a brightly lit room, and the third to a pitch black room." << endl;
cout << "\nWhat do you do?" << endl;
}
}
}
Basically just store whether the game is over or not in gameOver. Instead of calling gameOver(), just set this new gameOver variable to 1 (which means true). Then, later, you can check whether the game is over or not and skip everything else if it is.