Not displaying a chosen selection from a list? - c++

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.

Related

C++ How to align multiple output?

I have a problem to solve where I need to show the output in this format:
But the problem I am facing is that for Purchase ID: 2, which has two book title, the second book title (Midnight Library) is shown in second line and does not align properly, how can I align it under the Book Title?
Code:
void viewPurchase() //View all purchase transactions
{
system("cls");
struct purchaseInfo* viewPurchase;
viewPurchase = head;
int choice;
cout << "*************" << endl;
cout << "VIEW PURCHASE" << endl;
cout << "*************" << endl;
cout << "1. View Purchase" << endl;
cout << " " << endl;
cout << "0. BACK TO MENU" << endl;
cout << "\nEnter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
{
if (viewPurchase == NULL) {
cout << "No record in the list\n";
cout << "\nPress ENTER to Back to Menu...\n" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.get();
}
while (viewPurchase != NULL) {
cout << "============================================================================\n";
cout << "Purchase ID \tBook Title \t\t Total Item \tTotal Price\n";
cout << "============================================================================\n";
while (viewPurchase != NULL) {
cout << left << setw(16) << viewPurchase->purchaseID;
for (int loop = 0; loop < viewPurchase->size; loop++) {
cout << left << setw(30) << viewPurchase->book[loop].bookTitle;
if (loop == 0) {
cout << left << setw(18) << viewPurchase->totalItem;
cout << left << setw(16) << viewPurchase->totalPrice;
}
cout << endl;
}
viewPurchase = viewPurchase->next;
}
}
break;
}
case 0:
break;
default:
cout << "\nInvalid selection. Press ENTER to continue...\n" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.get();
break;
}
};
Anything need to change for this code?
cout << left << setw(30) << viewPurchase->book[loop].bookTitle;
but the second book title (Midnight Library) run away and does not align properly, how can I align it under the book Title?
Insert an empty string, using setw matching the width of the first column before inserting the book title.

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.

how to end the repetition of showing the menu in c++?

So, I am new to C++. I have this code where I need to input what I would like to view. What happened in my code is that, when I put an input in choice, for example 1, it will show the Peripherals list. And when I input 5 in the Peripheral List, it would go back to the Main Menu. In the Main Menu, if I inputted 4, the Main Menu is looping or repeating again and again. I need to exit it or end if I input 4.
#include <iostream>
using namespace std;
int main()
{
int choice;
int pick;
char view;
cout << "\n" << endl;
cout << "\t \t -------------------------------------------------------------------" << endl;
cout << "\t \t \t \t \t WELCOME TO SHOPPING SPREE" << endl;
cout << "\t \t -------------------------------------------------------------------" << endl;
//MENU
do {
cout << "What type of items would you like to view?" << endl;
cout << " [1] Peripherals" << endl;
cout << " [2] Mobile Phones" << endl;
cout << " [3] Consoles" << endl;
cout << " [4] Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if (choice == 1) {
cout << "\n";
cout << "What peripherals would you like to purchase?" << endl;
cout << "[1] HyperX Alloy FPS PRO" << endl;
cout << "[2] SteelSeries APEX PRO" << endl;
cout << "[3] Razer Kraken X" << endl;
cout << "[4] AORUS K7" << endl;
cout << "[5] BACK TO MENU" << endl;
cout << "Enter your choice: ";
cin >> pick;
}
else if (choice == 2) {
cout << "\n";
cout << "What mobile phones would you like to purchase?" << endl;
cout << "[1] Xiaomi Mi Mix 3" << endl;
cout << "[2] Oppo Reno" << endl;
cout << "[3] Realme 5" << endl;
cout << "[4] Samsung Galaxy 10" << endl;
cout << "[5] BACK TO MENU" << endl;
cout << "Enter your choice: ";
cin >> pick;
}
else if (choice == 3) {
cout << "\n";
cout << "What consoles would you like to purchase?" << endl;
cout << "[1] PlayStation 5" << endl;
cout << "[2] Nintendo Switch" << endl;
cout << "[3] PlayStation 4" << endl;
cout << "[4] XBOX S" << endl;
cout << "[5] BACK TO MENU" << endl;
cout << "Enter your choice: ";
cin >> pick;
}
}
while (pick == 5);
}
You need to do a thing when choice is 4 (currently you're not doing anything).
That thing is break: end the loop.
else if (choice == 4) {
break;
}
Alternatively, build it into the loop condition:
while (choice != 4 && pick == 5);
…though, personally, I think this is harder to follow.
The break in C or C++ is a loop control statement which is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stops there and control returns from the loop immediately to the first statement after the loop.
So, you simply can do:
cout << "What type of items would you like to view?" << endl;
cout << " [1] Peripherals" << endl;
cout << " [2] Mobile Phones" << endl;
cout << " [3] Consoles" << endl;
cout << " [4] Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if (choice == 4) {
break;
}

Returned values are not the same as written out

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.

Why will my program not re-enter my 2nd while loop? C++ [closed]

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';
....