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.
Related
My C++ program wants the user to choose a test option. Option A wants the user to login their id, then they will proceed to take the test. Option B gives the user the results of the taken test. Finally, Option C will make the user quit.
I am trying to get the function getStatistics() to display whether the question that what the user answered is right or wrong, display the user answers and the correct answer.
`
#include <iostream>
#include <string>
# include <cctype>
using namespace std;
const int SIZE = 8;
int totalRightScore{};
int result = totalRightScore;
char ch;
char answer[SIZE] = { 'a', 'b', 'c', 'd' , 'A' , 'B' , 'C' , 'D' };
void test() {
char choice;
cout << "1. What is the capital of USA?" << endl;
cout << "(a)Georgia" << endl;
cout << "(b)Washington, Dc" << endl;
cout << "(c)Berlin" << endl;
cout << "(d)New York City" << endl;
cin >> ch;
if (ch == answer[1] || ch == answer[5]) {
totalRightScore = totalRightScore + 1;
}
cout << "2. How many stars has the USA flag have" << endl;
cout << "(a)50" << endl;
cout << "(b)60" << endl;
cout << "(c)35" << endl;
cout << "(d)13" << endl;
cin >> ch;
if (ch == answer[0] || ch == answer[4]) {
totalRightScore = totalRightScore + 1;
}
cout << "3. What is the name of your SQL instructor?" << endl;
cout << "(a)Alan Anderson" << endl;
cout << "(b)Dr House " << endl;
cout << "(c)Bill Nye" << endl;
cout << "(d)Dr Gill" << endl;
cin >> ch;
if (ch == answer[0] || ch == answer[4]) {
totalRightScore = totalRightScore + 1;
}
}
void loginid() {
string login = "test123";
cout << "enter your login id" << endl; ;
cin >> login;
if (login == "test123") {
test();
}
else
{
cout << "Sorry wrong user ID";
}
}
void getStatistics() {
cout << " Question 1 ";
if (ch == answer[1] || ch == answer[5]) {
cout << "correct" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(b) Washington, Dc" << endl;
}
else
{
cout << "incorrect" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(b)Washington, Dc" << endl;
}
cout << " Question 2 ";
if (ch == answer[0] || ch == answer[4]) {
cout << "correct" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(a) 50" << endl;
}
else
{
cout << "incorrect" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(a) 50" << endl;
}
cout << " Question 3 ";
if (ch == answer[0] || ch == answer[4]) {
cout << "correct" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(a)Alan Anderson" << endl;
}
else
{
cout << "incorrect" << endl;
cout << "your answer is " << endl;
cout << ch << endl;
cout << "correct answer is " << endl;
cout << "(a)Alan Anderson" << endl;
}
result = totalRightScore;
cout << "your total score is " << result << "/3 " << endl;
totalRightScore = 0;
}
void exit() {
char choice;
cout << "Press Q or q to exit program." << endl;
cin >> choice;
if (choice == 'Q'|| choice == 'q')
{
cout << "Good bye Now" << endl;
}
}
void menu() {
string keepgoing = "y";
char choice;
while (keepgoing == "y")
{
cout << " Select Your Option:\n ";
cout << "(a Login with your userID\n ";
cout << "(b Statistics\n ";
cout << "(c Quit\n ";
cin >> choice;
switch (choice)
{
case 'a':
loginid();
break;
case 'b':
getStatistics();
break;
case 'c':
exit();
break;
}
cout << "would you like to continue? type 'y' to continue " << endl;
cin >> keepgoing;
}
}
`
The problem is that getStatistics() is just getting the last input from test(), for example if you input the right answer for question 1 and input the right answer question 3, when you run the getStatistics()it only remembers the last input from test() and thus deem the right answer for question 1 incorrect. Is there anyway for the getStatistics() to remember all the user answers for all the questions from test(), instead of just getting what is last answered.Thank you.
So I've been writing a program and it's almost done but I met with a trouble. I am a beginner in programming so the code is not written perfectly, I don't even know classes. The program has many Polish things but I tried to translate some so there should not be any problem with understanding.
And yes, I used using namespace std; here, I know it is a bad practise, sorry.
#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <cctype>
#include <conio.h>
#include <fstream>
#include <random>
#include <chrono>
#include <string>
using namespace std;
char startLUBwyjscie; //startORexit
char yesorno;
int mojeHP = 100, HPosmiornicy = 100, mojaEN = 100; //myHP, Octopu'sHP, myENERGY
int wyborAtaku; //choosingTheAttack
char clickO;
//char spamX; not useful now
char clickanything;
char clickanything2;
char clickanything3; //idk if 3 variables are necessary but made it in case of problems
ofstream zapisfout; //for saving smth to the file
ifstream odczytfin; //for reading-out smth from the file
string wartoscdoodczytu; //AValueToRead-out
int liniapliku = 0; //LineOfFile
char choosethelanguage;
int PowerfulPunch(); //prototypes
int KnifeThrow();
int NormalAttack();
int OctopusAttack();
int WhosNext();
unsigned ziarno_liczb_losowych = std::chrono::steady_clock::now().time_since_epoch().count(); //seed
default_random_engine silnik_liczb_losowych(ziarno_liczb_losowych); //engine
int main()
{
cout << "Wybierz jezyk / Choose the language" << endl;
cout << "1. Polski (bez polskich znakow) / Polish (without Polish characters)" << endl; //does not exist, a limit of characters in my post has been exceeded so I had to delete this option
cout << "2. English / Angielski" << endl; //click 2 always
choosethelanguage = _getch(); //choose the language
if (choosethelanguage == '2') //English version
{
system("cls");
menu: //label
srand(time(NULL));
cout << "DEPTH OF ABYSSAL SEA" << endl << endl;
cout << "1. Start" << endl;
cout << "2. Instructions" << endl;
cout << "3. Read-out logs of the last fight" << endl;
cout << "4. Credits" << endl;
cout << "5. Exit" << endl;
startLUBwyjscie = _getch(); //menu
switch (startLUBwyjscie)
{
case '1': //a story and the game
{
system("cls");
cout << "Do you want to pass over the exordium? Click 'X' to pass over the exordium. Click anything else to read the exordium." << endl;
yesorno = _getch();
if (yesorno == 'X' || yesorno == 'x') //pass over the exordium (y/n)
goto koniecwstepu; //go to the label
else //exordium (story)
{
system("cls");
cout << "The strory begins so many years ago." << endl;
Sleep(2500);
cout << "You are Felix. You are nineteen years old." << endl;
Sleep(2500);
cout << "You were born on Malta - country situated on the Mediterraen Sea. Simply a little island." << endl;
Sleep(2500);
cout << "Your grandfather told you a story which was about the Atlantis." << endl;
Sleep(2500);
cout << "It seemed like a fairy tale, something, what doesn't even exist." << endl;
Sleep(2500);
cout << "It was told that the Atlantis was situated on the Arctic Ocean. It seemed to be a long way from here." << endl;
Sleep(2500);
cout << "But the story was told many years ago, when you were eight. Your grandfather died several years ago." << endl;
Sleep(2500);
cout << "It is touching, isn't it?" << endl;
Sleep(2500);
cout << "But even when you were growing up, you didn't stop believing in the story." << endl;
Sleep(2500);
cout << "You are too young to see some things. You look from the shallow perspective." << endl;
Sleep(2500);
cout << "You demand an adventure! You think that you are the chosen one. The chosen one to know the secret." << endl;
Sleep(2500);
cout << "You took every things that might be useful in case of meeting ruins of destroyed continent." << endl;
Sleep(2500);
cout << "But will you able to rise to the challenge?" << endl;
Sleep(2500);
cout << "Let's see..." << endl;
Sleep(10000);
koniecwstepu: //label
system("cls");
}
zapisfout.open("Logs of the last fight.txt", ios::trunc); //deleting the content before next informations
zapisfout.close(); //closing file
//the game
for (int i = 1; ((mojeHP <= 100 && mojeHP > 0) && (HPosmiornicy <= 100 && HPosmiornicy > 0)); i++)
{
if (i == 1)
{
cout << "Your HP: " << mojeHP << endl;
cout << "Your Energy: " << mojaEN << endl << endl;
cout << "Octopus' HP: " << HPosmiornicy << endl << endl << endl;
}
blad: //label blad (błąd means error in this case but I cannot use polish characters so I named the label 'blad')
cout << "Round " << i << endl;
if (WhosNext() == 1)
cout << "Your turn" << endl << endl;
else
cout << "Octopus' turn" << endl << endl;
cout << "Available actions: " << endl;
cout << "1. Powerful punch (-30 Energy)" << endl;
cout << "2. Knife throw (-45 Energy)" << endl;
cout << "3. Normal attack (+30 Energy)" << endl;
wyborAtaku = _getch();
cout << endl << endl;
if (wyborAtaku == '1') // Powerful Punch
{
if (mojaEN - 30 <= 0)
{
cout << "You don't have enough energy!" << endl << endl << endl; //brak energii
goto blad; //go to the label
}
cout << "You deal " << PowerfulPunch() << " damage to the octopus." << endl;
cout << "The octopus deals you " << OctopusAttack() << " damage." << endl << endl << endl;
mojeHP -= OctopusAttack(); //substract my HP
mojaEN -= 30; //substract the energy
HPosmiornicy -= PowerfulPunch(); //substract octpus' HP
if (mojeHP <= 0)
cout << "Your HP: 0" << endl; //showing my HP <0
else
cout << "Your HP: " << mojeHP << endl; //showing my HP >0
cout << "Your Energy: " << mojaEN << endl << endl; //showing my energy
if (mojeHP <= 0)
cout << "Octopu's HP: 0" << endl; //showing octopus' HP <0
else
cout << "Octopus' HP: " << HPosmiornicy << endl << endl << endl; //showing octopus' HP >0
}
else if (wyborAtaku == '2') // Knife throw
{
if (mojaEN - 45 <= 0)
{
cout << "You don't have enough energy!" << endl << endl << endl;
goto blad;
}
cout << "You deal " << KnifeThrow() << " damage to the octopus." << endl;
cout << "The octopus deals you " << OctopusAttack() << " damage." << endl << endl << endl;
mojeHP -= OctopusAttack(); //substract my HP
mojaEN -= 45; //substract the energy
HPosmiornicy -= KnifeThrow(); //substract octpus' HP
if (mojeHP <= 0)
cout << "Your HP: 0" << endl; //showing my HP <0
else
cout << "Your HP: " << mojeHP << endl; //showing my HP >0
cout << "Your Energy: " << mojaEN << endl << endl; //showing my energy
if (mojeHP <= 0)
cout << "Octopu's HP: 0" << endl; //showing octopus' HP <0
else
cout << "Octopus' HP: " << HPosmiornicy << endl << endl << endl; //showing octopus' HP >0
}
else if (wyborAtaku == '3') // Normal attack
{
cout << "You deal " << NormalAttack() << " damage to the octopus." << endl;
cout << "The octopus deals you " << OctopusAttack() << " damage." << endl << endl << endl;
mojeHP -= OctopusAttack(); //substract my HP
mojaEN += 30; //adding the energy
HPosmiornicy -= NormalAttack(); //substract octpus' HP
if (mojeHP <= 0)
cout << "Your HP: 0" << endl; //showing my HP <0
else
cout << "Your HP: " << mojeHP << endl; //showing my HP >0
cout << "Your Energy: " << mojaEN << endl << endl; //showing my energy
if (HPosmiornicy <= 0)
cout << "Octopus' HP: 0" << endl; //showing octopus' HP <0
else
cout << "Octopus' HP: " << HPosmiornicy << endl << endl << endl; //showing octopus' HP >0
}
else if ((wyborAtaku != '1' && wyborAtaku != '2' && wyborAtaku != '3') || !isdigit(wyborAtaku))
{
cout << "Incorrect character!" << endl << endl << endl;
goto blad;
}
zapisfout.open("Logs of the last fight.txt", ios::app); //opening the file and actualizing date in it
zapisfout << "Round " << i << endl;
if (mojeHP <= 0)
zapisfout << "Your HP: 0" << endl; //showing my HP <0 in file
else
zapisfout << "Your HP: " << mojeHP << endl; //showing my HP >0 in file
zapisfout << "Your Energy: " << mojaEN << endl; //showing my energy in file
if (HPosmiornicy <= 0)
zapisfout << "Octopus' HP: 0" << endl; //showing octopus' HP <0 in file
else
zapisfout << "Octopus' HP: " << HPosmiornicy << endl << endl << endl; //showing octopus' HP >0 in file
zapisfout.close(); //closing the file
}
if ((HPosmiornicy <= 0 && WhosNext() == 1 && mojeHP <= 0) || (HPosmiornicy <= 0 && (WhosNext() == 2 || WhosNext() == 1) && mojeHP > 0))
{
cout << endl << endl;
cout << "VICTORY!!!" << endl << endl;
Sleep(2500);
cout << "What?! It's impossible!" << endl;
Sleep(2500);
cout << "Some feeble human could slay that enermous creature?" << endl;
Sleep(2500);
cout << "I can't believe..." << endl;
Sleep(2500);
cout << "You had actually nothing brought from your home..." << endl;
Sleep(2500);
cout << "Some food and drink, diving disguise and some blunt knives..." << endl;
Sleep(2500);
cout << "This world is impressive and never will stop surprising me." << endl;
Sleep(2500);
cout << "You see how the octopus is sinking in the sand. You can take your treasure!" << endl;
Sleep(2500);
cout << "You deserve, to be honest." << endl;
Sleep(2500);
cout << "Hey, let's make it! Open it!" << endl << endl;
Sleep(2500);
cout << "*CLICK 'O' TO OPEN*" << endl;
open: //label 'open'
clickO = _getch();
if (clickO == 'o' || clickO == 'O')
{
cout << endl;
cout << "You made it! Wow... These are truly beatiful..." << endl;
Sleep(2500);
cout << "You are so wealthy right now..." << endl;
Sleep(2500);
cout << "Golden ingots, diamond trident and some gems..." << endl;
Sleep(2500);
cout << "Wow... I haven't seen the things like that since billions years..." << endl; //Look at your oxygen in your bottle! You are getting strangled! SWIM UP, SWIM UP!!!"<<endl<<endl; //not really important here now
Sleep(2500);
//cout<<"*SPAM 'X' TO SWIM UP (25 to get out in 10 seconds)* "<<endl; //not really important here now
cout << "It's time for you now. Congratulations." << endl << endl;
Sleep(2500);
cout << "GOOD ENDING" << endl << endl;
zapisfout.open("Logs of the last fight.txt", ios::app);
zapisfout << "GOOD ENDING" << endl; //actualizing data in the file with an ending
zapisfout.close(); //closing the file
Sleep(10000);
}
else
{
cout << "*WRONG CHARACTER!*" << endl << endl;
goto open; //coming back to 'open' label
}
}
else if ((HPosmiornicy <= 0 && WhosNext() == 2 && mojeHP <= 0) || (HPosmiornicy > 0 && (WhosNext() == 2 || WhosNext() == 1) && mojeHP <= 0))
{
cout << endl << endl;
cout << "DEFEAT!!!" << endl << endl;
cout << "Happened. You died. You are a ghost." << endl;
Sleep(2500);
cout << "Impossible?" << endl;
Sleep(2500);
cout << "For sure you are wondering how it happened..." << endl;
Sleep(2500);
cout << "For sure you are wondering where you are now..." << endl;
Sleep(2500);
cout << "HELLO?!" << endl;
Sleep(2500);
cout << "No one hears you. It is the world of the all dead beings such as people but also animals." << endl;
Sleep(2500);
cout << "Don't worry. You can't die here. It wouldn't be logical. But you can be vexed by other creatures living here." << endl;
Sleep(2500);
cout << "Now you can worry." << endl;
Sleep(2500);
cout << "What happened to the octopus, you probably wonder." << endl;
Sleep(2500);
cout << "It is still alive and it is waiting for other daredevils that will think that they are, as you named it, 'the chosen ones'. Funny cycle, isn't it?" << endl;
Sleep(2500);
cout << "Sorry, you didn't manage to slay the creature." << endl;
Sleep(2500);
cout << "You were too weak." << endl;
Sleep(2500);
cout << "Oh look! Something approaches to you! Looks known..." << endl;
Sleep(2500);
cout << "-I said that the Atlantis had existed..." << endl << endl;
Sleep(2500);
cout << "BAD ENDING" << endl << endl;
zapisfout.open("Logs of the last fight.txt", ios::app);
zapisfout << "BAD ENDING" << endl; //actualizing data in the file with an ending
zapisfout.close(); //closing the file
Sleep(10000);
}
break;
}
case '2': //just explaining the game
{
system("cls");
cout << "You start the game in menu. There you can choose an option:" << endl;
cout << "1. Start, if you want to start the game." << endl;
cout << "2. Instructions, if you want to know how to play the game, the place where you are now." << endl;
cout << "3. Read-out logs of the last fight to see the course of the latest battle." << endl;
cout << "4. Exit, if you want to go out of the game." << endl << endl;
cout << "After clicking Start you are going to see the exordium which you can pass over by clicking 'x'." << endl;
cout << "The exordium brings you into the main story." << endl;
cout << "In game, you have three bars:" << endl;
cout << "Your HP" << endl;
cout << "Your Energy" << endl;
cout << "Octopus' HP" << endl;
cout << "The bars show the level of your health points, your energy points and octopus' health points." << endl;
cout << "Your HP goes down when octopus attacks you." << endl;
cout << "Your energy is spent by using your abilities." << endl;
cout << "Octopus' HP goes down when you attack it." << endl;
cout << "All abilities always deal damage, there cannot be a situation when the skills deal 0 damage." << endl;
cout << "All values on the start are equal 100." << endl;
cout << "Every dealt damage is generated by random numbers or psuedorandom numbers. It all depends of RNG god." << endl;
cout << "Your character has 3 spells: " << endl;
cout << "1. Powerful Punch" << endl;
cout << "This spell uses 30 of your energy and deals 20-35 damage." << endl;
cout << "2. Knife Throw" << endl;
cout << "This spell uses 45 of your energy and deals 36-50 damage." << endl;
cout << "3. Normal Attack" << endl;
cout << "This spell gives you 30 energy and deals 1-15 damage." << endl;
cout << "The octopus doesn't have any special attacks but it always deals damage 1-50 damage." << endl;
cout << "As it was told, octopus doesn't have any special attacks, so it doesn't have energy points too." << endl;
cout << "The battle is split on rounds." << endl;
cout << "Every round is began by the octopus or by you, all depends of drawn order." << endl;
cout << "If Your HP and Octopus' HP are equal 0, then drawn order decides about victory and defeat." << endl << endl;
cout << "CLICK ANYTHING TO EXIT THE ISTRUCTIONS AND REGAIN TO THE MAIN MENU" << endl;
clickanything = _getch();
if (clickanything)
{
cout << "You will be brought to the main menu in a moment." << endl;
Sleep(2500);
system("cls");
goto menu; //going to the 'menu' label
}
break;
}
case '3': //file
{
system("cls");
odczytfin.open("Logs of the last fight.txt"); //opening the file
if (!odczytfin.is_open())
{
cout << "It was not able to open the file! You will be brought to the main menu in a moment." << endl;
Sleep(2500);
system("cls");
goto menu; //going to the 'menu' label
}
while (odczytfin.good()) //checking if the file is okay
{
liniapliku++;
getline(odczytfin, wartoscdoodczytu);
cout << wartoscdoodczytu << endl;
}
if (odczytfin.eof()) //if eof(), click anything
{
cout << endl << endl;
cout << "CLICK ANYTHING TO EXIT THE LOGS AND REGAIN TO THE MAIN MENU" << endl;
clickanything2 = _getch();
if (clickanything2)
{
cout << "You will be brought to the main menu in a moment." << endl;
Sleep(2500);
system("cls");
goto menu; //going to the 'menu' label
}
}
odczytfin.close(); //closing the file
}
case '4': //credits
{
system("cls");
cout << "The game was whole made by Vatnax. (and the guys who helped me with a problem)" << endl << endl;
cout << "CLICK ANYTHING TO EXIT THE CREDITS AND REGAIN TO THE MAIN MENU" << endl;
clickanything3 = _getch();
if (clickanything3)
{
Sleep(2500);
system("cls");
goto menu; //going to the 'menu' label
break;
}
}
case '5': //exit
{
exit(0);
break;
}
default: //if input wrong value in a menu
{
cout << "Incorrect value! You will be brought to the main menu in a moment." << endl;
Sleep(2500);
system("cls");
goto menu; //going to the 'menu' label
break;
}
}
}
}
//functions
int PowerfulPunch()
{
uniform_int_distribution<int> dystrybutor_liczb_losowych(20, 35); //distributor of a random number
return dystrybutor_liczb_losowych(silnik_liczb_losowych); //returning this number with the engine and the seed which are declared on the beginning of the code
}
int KnifeThrow()
{
uniform_int_distribution<int> dystrybutor_liczb_losowych(36, 50); //distributor of a random number
return dystrybutor_liczb_losowych(silnik_liczb_losowych); //returning this number with the engine and the seed which are declared on the beginning of the code
}
int NormalAttack()
{
uniform_int_distribution<int> dystrybutor_liczb_losowych(1, 15); //distributor of a random number
return dystrybutor_liczb_losowych(silnik_liczb_losowych); //returning this number with the engine and the seed which are declared on the beginning of the code
}
int OctopusAttack()
{
uniform_int_distribution<int> dystrybutor_liczb_losowych(1, 50); //distributor of a random number
return dystrybutor_liczb_losowych(silnik_liczb_losowych); //returning this number with the engine and the seed which are declared on the beginning of the code
}
int WhosNext() //responsible for who starts the round
{
uniform_int_distribution<int> dystrybutor_liczb_losowych(1, 2); //distributor of a random number
return dystrybutor_liczb_losowych(silnik_liczb_losowych); //returning this number with the engine and the seed which are declared on the beginning of the code
}
It's the long code, but half of this is a Polish version of the program.
The problem is that the values returned from functions are subtracted later from current mojeHP variable state. After it, mojeHP is shown but it doesn't have the value as it should have. It is all made in the lines 146-162, 173-189, 195-211.
I copied the whole code because I don't even know where the problem is so maybe all the code will be needed, not only a piece of it.
E.g.:
Your HP: 100
Your Energy: 100
Octopus' HP: 100
Round 1
Your turn
Available actions:
Powerful punch (-30 Energy)
Knife throw (-45 Energy)
Normal attack (+30 Energy)
You deal 15 damage to the octopus.
The octopus deals you 12 damage.
Your HP: 66 // 100 - 12 is not equal 66
Your Energy: 130 // this one is written out as it should have been because there is always added 30 energy in this case
Octopus' HP: 91 // 100 - 15 is not equal 91
The relevant code seems to be:
cout << "You deal " << NormalAttack() << " damage to the octopus." << endl;
cout << "The octopus deals you " << OctopusAttack() << " damage." << endl << endl << endl;
mojeHP -= OctopusAttack(); //substract my HP
mojaEN += 30; //adding the energy
HPosmiornicy -= NormalAttack(); //substract octpus' HP
Each time you call NormalAttack() a new random number is generated. As you are calling it twice you get 2 numbers, print one and use the other to update the hit points. Your code should be:
auto myAttack = NormalAttack();
auto enemyAttack = OctopusAttack();
cout << "You deal " << myAttack << " damage to the octopus." << endl;
cout << "The octopus deals you " << enemyAttack << " damage." << endl << endl << endl;
mojeHP -= enemyAttack; //substract my HP
mojaEN += 30; //adding the energy
HPosmiornicy -= myAttack; //substract octpus' HP
There is no need to have a copies of your code for each language, just put all your language strings in an array or map and choose which array to use to change the language (or for a real project use an internationalisation framework). e.g. something like this:
std::map<std::string, std::string> english =
{
{ "hello", "Hello" },
{ "goodbye", "Goodbye" },
};
std::map<std::string, std::string> polish =
{
{ "hello", "Witaj" },
{ "goodbye", "Do widzenia" },
};
auto& language = choosethelanguage == '2' ? english : polish;
std::cout << language["hello"] << "\n";
std::cout << language["goodbye"] << "\n";
You'd probably want to wrap the string lookup into a function to check for invalid values and return back the key instead of the empty string that would result from the above code.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
All of my commands and alters to the array work individually. However, when i try to return to the menu the screen just starts jittering and will not continue. I am forced to close the program. How do i fix this.
/* Programmer: Joshua Zuber
Program Desc: This Program will allow the user to select an icon to display around an array message!
Program Name: Array Demonstration
Clean Compile Date:
*/
#include<iostream>
#include<string>
#include<iomanip>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
// Arrays
string Masterfile[] = "I want to thank all the C++ students who has helped me this semester. You have inspired me to work harder and to be able to design small C++ programs using a gamming approach. ";
string Studentfile[]= "";
// Variables
int Icon;
char again = 'y';
int i;
int j;
int menu = 'y';
int menu2 = 'n';
int menu3 = 'n';
int menu4 = 'n';
int menu5 = 'n';
int objEdit;
while (toupper(again) == 'Y') // Start Main Loop
{
cout << "Welcome to Array Demonstration!" << "\n\n";
cout << Masterfile[0] << "\n\n";
while(toupper(menu) == 'Y' || toupper(menu2) == 'Y' || toupper(menu3) == 'Y' || toupper(menu4) == 'Y' || toupper(menu5) == 'Y' ) // Start Array Menu Loop
{
cout << "Please select one of the below options to edit this string!" << "\n\n";
Studentfile[0] = Masterfile[0];
cout << "1. Size" << "\n\n";
cout << "2. Replace {all of the C++ students} with {My instructer, Professor Penn}" << "\n\n";
cout << "3. Swap the word {small} with {efficient}" << "\n\n";
cout << "4. Erase the phrase {using a gamming approach}" << "\n\n";
cout << "5. View Final Product" << "\n\n";
cin >> objEdit;
if(objEdit == 1) // Menu Array Size Check
{
cout << "The size of the original string is: " << Masterfile[0].size() << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu2 ;
system("cls");
}
else if(objEdit == 2) // Menu 2nd Option
{
cout << "Changing the phrases!" << "\n\n";
Studentfile[0].replace(16,20,"My instructer, Professor Penn");
cout << Studentfile[0] << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu3;
system("cls");
}
else if(objEdit == 3) // Menu 3rd Option
{
cout << "Changing the phrases!" << "\n\n";
Studentfile[0].replace(131,5,"efficient" );
cout << Studentfile[0] << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu4;
system("cls");
}
else if(objEdit == 4) // Menu 3rd Option
{
cout << "Changing the phrases!" << "\n\n";
Studentfile[0].erase(150);
cout << Studentfile[0] << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu5;
system("cls");
}
else if (objEdit <=0 || objEdit >=6) // Menu Failsafe
{
cout << "Please Select a Valid Number" << "\n\n";
cout << "1. Size" << "\n\n";
cout << "2. Replace {all of the C++ students} with {My instructer, Professor Penn}" << "\n\n";
cout << "3. Swap the word {small} with {efficient}" << "\n\n";
cout << "4. Erase the phrase {using a gamming approach}" << "\n\n";
cout << "5. View Final Product" << "\n\n";
cin >> objEdit;
}
else if(objEdit == 5 || toupper(menu) == 'N') // Menu 5th Option
{
cout << "Please Select one of the following numbers to choose a symbol!" << "\n\n";
cout << "1. *" << "\n\n";
cout << "2. ^" << "\n\n";
cout << "3. #" << "\n\n";
cout << "4. +" << "\n\n";
cin >> Icon;
system("cls");
if(Icon <= 0, Icon >= 5) // User Failsafe
{
cout << "You're Entry Is Not Valid" << "\n\n";
cout << "Please Select one of the following numbers to choose a symbol!" << "\n\n";
cout << "1. *" << "\n\n";
cout << "2. ^" << "\n\n";
cout << "3. #" << "\n\n";
cout << "4. +" << "\n\n";
cin >> Icon;
system("cls");
}
else // Icon Breakdown
{
if(Icon == 1) // Icon Choice 1
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "*******************************************************************************" << "\n";
cout << Studentfile[0] << "\n";
cout << "*******************************************************************************" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else if(Icon == 2) // Icon Choice 2
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << "\n";
cout << Studentfile[0] << "\n";
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else if(Icon == 3) // Icon Choice 3
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "###############################################################################" << "\n";
cout << Studentfile[0] << "\n";
cout << "###############################################################################" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else if(Icon == 4) // Icon Choice 4
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << "\n";
cout << Studentfile[0] << "\n";
cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else // Icon Choice 5
{
cout << "Sorry You Didn't Want to Play" << "\n\n";
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
} // End Menu Loop
} // End Main Loop
cout << "Thank you for playing!" << "\n\n";
system("pause");
return 0;
}
Probably because you define menu .. menu5 as int. Try:
char menu = 'y';
char menu2 = 'n';
char menu3 = 'n';
char menu4 = 'n';
char menu5 = 'n';
....
So were being asked to make a game in my C++ class, I took a C++ class awhile ago so I am a little rusty. I remember that you can use arrays and lists?
The point of the game is to choose an army faction, choose the army type, then attack someone. Once I get to the attack part, instead of making a bunch of if statements checking for the chosen faction from the previous menu, could I implement the factions into an array from the beginning of the program and once I get to the attack stage, run through the array and compare the user chosen continent with the continents in the array and just withhold an output that matches?
If someone could post a little code or link to a website that gives an example of something like this it would be greatly appreciated, I want to do it myself, I don't really something fully typed out for me.
#include <iostream>
using namespace std;
int main() {
// Declare variables
int menuInput = 0, continentInput = 0, armyInput = 0, actionInput = 0;
// Intro
cout << "WELCOME TO WAR" << endl;
// Display main menu
do {
cout << "1) Rules" << endl;
cout << "2) Play Game" << endl;
cout << "3) Quit" << endl;
cout << "Menu choice: ";
cin >> menuInput;
// if rules is selected
if (menuInput == 1) {
cout << endl;
cout << "RULES: " << endl;
cout << "1) Choose your player." << endl;
cout << "2) Choose your army type." << endl;
cout << "3) Choose to attack." << endl;
cout << endl;
}
// if game is selected
else if (menuInput == 2) {
cout << endl;
cout << "START" << endl;
// first do while loop, continent choice
do {
cout << "1) North America" << endl;
cout << "2) South America" << endl;
cout << "3) Europe" << endl;
cout << "4) Africa" << endl;
cout << "5) Asia" << endl;
cout << "6) Australia" << endl;
cout << "7) Antartica" << endl;
cout << "Choose your player from the list: ";
cin >> continentInput;
cout << endl;
// invalid display if selection not in range
if (continentInput <= 0 ||continentInput > 7) {
cout << "INVALID" << endl;
cout << endl;
}
} while (continentInput <= 0 || continentInput > 8);
// second do while loop, army type choice
do {
cout << "1) Army (Ground type forces)" << endl;
cout << "2) Navy (Sea type forces)" << endl;
cout << "3) Air Force (Air type forces)" << endl;
cout << "Choose your army type from the list: ";
cin >> armyInput;
cout << endl;
if (armyInput <= 0 || armyInput > 3) {
cout << "INVALID" << endl;
}
} while (armyInput <= 0 || armyInput > 3);
// third do while loop, who to attack
}
else if (menuInput == 3) {
cout << endl;
cout << "GAME OVER" << endl;
}
else {
// display invlaid input if number choice is not in given range
cout << "INAVLID INPUT" << endl;
}
} while (menuInput != 3);
return 0;
}
If you change your user input to a number you can reference an array filled with the choices.
military[x] = { "Army", "Navy" ...};
fromWhere[x] = { "North America", "South" ...};
toKill[x] = { "Whoever has oil" ... };
//get user input.
//toKill[get user input];
//kill with military[get user input];
//kill form fromWhere[get user input];
//do some attack logic
Just a heads up your question is rather vague. Can you clarify what you need. It seems you wish to hash your values and do a quick lookup to avoid string comparison but you don't need to because you are grabbing an int as user input.
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.