How to receive key input without requiring ENTER? [duplicate] - c++

This question already has answers here:
C++ cin keypress event
(4 answers)
Capture characters from standard input without waiting for enter to be pressed
(21 answers)
Closed 8 years ago.
i=0;
while(i<=20)
{
nullchoice:
system("CLS");
//Advanced Information
cout << "Your Statistics: " << endl;
cout << endl << endl;
cout << " 1 Strength: " << str << endl;
cout << endl;
cout << " 2 Vitality: " << vit << endl;
cout << endl;
cout << " 3 Agility: " << agi << endl;
cout << endl;
cout << " 4 Thaumaturgy: " << tha << endl;
cout << endl << endl;
cout << "Points Remaining: " << lvlskills << endl;
cout << endl;
cout << "Enter the number of the skill you wish to increase: ";
//Applying points to skill attributes
if(i<=19)
{
cin >> input;
if(input==1)
str+=1;
else if(input==2)
vit+=1;
else if(input==3)
agi+=1;
else if(input==4)
tha+=1;
else
goto nullchoice;
lvlskills-=1;
}
i++;
cout << endl << endl;
}
So essentially, I am creating a game in C++, a text-based RPG. It's fairly basic, with stats (Strength, Vitality, etc.) you might expect from such a game. In the beginning, as shown here, the player is allowed to distribute some points to skills they choose.
Here's where the problem arises. Right now, the player must enter a number (1, 2, 3, or 4. If it's none of these numbers it will goto the nullchoice), then press ENTER. It's unwieldy and just plain wrong to have the player do this, so is there any simple way that I can code it so they only have to press the number?
I'd imagine I would use this very much throughout the rest of my game. Thanks for reading!

You just need to store the input and compare it to the required case. Put a think on it...
do
{
system("CLS");
//Advanced Information
cout << "Your Statistics: " << endl;
cout << endl << endl;
cout << " 1 Strength: " << str << endl;
cout << endl;
cout << " 2 Vitality: " << vit << endl;
cout << endl;
cout << " 3 Agility: " << agi << endl;
cout << endl;
cout << " 4 Thaumaturgy: " << tha << endl;
cout << endl << endl;
cout << "Points Remaining: " << lvlskills << endl;
cout << endl;
cout << "Enter the number of the skill you wish to increase: ";
//Applying points to skill attributes
char input;
switch(input=getch()){
case '1':
str+=1;
lvlskills-=1;
break;
case '2':
vit+=1;
lvlskills-=1;
break;
case '3':
agi+=1;
lvlskills-=1;
break;
case '4':
tha+=1;
lvlskills-=1;
}
cout << endl << endl;
} while(lvlskills>0);
Avoid goto in your code while you can solve it by other options. It's a good practice..

Related

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.

File pointer only read the first entry

Good day everyone. My program is about a Computer Shop (Laptop). So, people can buy laptop through this program and "PCPurchase" is the function that gonna handle the customer transaction.
I use file-pointer and struct to save information about all the laptops. And of course, the struct store more than 1 type of laptops because obviously this is a laptop shop.
I encounter a problem where user can only buy (enter name) of the first entry (first laptop) in the struct. Here: cout << "Enter the laptop company and name you want to buy: " << endl;
If customer enter the name of 2nd laptop,3rd and so on, it will jump to line
cout << endl << "\tNot available!" << endl; cout << "\tPress A to try again or B to return to main menu" << endl;
It indicates that the laptop's name is not in database which actually is.
Can I know what the problem here actually is?
int PCPurchase()
{
struct customer cust;
system("color 0A");
char laptop[100];
double total_bill;
const double TAX=0.06;
system("cls");
cout << setfill ('-') << setw (55) << "-" << endl;
cout << "\t\tCustomer Dashboard" << endl;
cout << setfill ('-') << setw (55) << "-" << endl;
fptr=fopen("laptop.txt","ab+");
cout << "Available laptops: " << endl;
rewind(fptr);
while(fread(&PC,sizeof(PC),1,fptr)==1)
{
cout << endl << "Laptop company and name: ";
cout << PC.laptopcompany << endl;
cout << "RAM: ";
cout << PC.RAM << endl;
cout << "Processor: ";
cout << PC.Processor << endl;
cout << "Price: RM";
cout << PC.price << endl;
}
cout << "\nPress any key to continue purchase" << endl;
getch();
fflush(stdin);
getInfo(cust); //get information of customer
cout << "Enter the laptop company and name you want to buy: " << endl;
cout << "(Type 'RETURN' if you do not want to purchase)" << endl << endl;
gets(laptop);
rewind(fptr);
while(fread(&PC,sizeof(PC),1,fptr)==1)
{
if(strcmpi(PC.laptopcompany,laptop)==0)
{
cout << setfill ('-') << setw (55) << "-" << endl;
cout << "\tYou have selected" << endl;
cout << setfill ('-') << setw (55) << "-" << endl;
cout << "Laptop company and name: ";
cout << PC.laptopcompany << endl;
cout << "RAM: ";
cout << PC.RAM << endl;
cout << "Processor: ";
cout << PC.Processor << endl;
cout << "Price: ";
cout << PC.price << endl;
total_bill=PC.price+(PC.price*TAX);
cout << setfill ('-') << setw (55) << "-" << endl;
cout << fixed << showpoint << setprecision (2);
cout << "Name: "<< cust.name << endl; // struct output
cout << "Email: "<< cust.email << endl;
cout << "Phone Number: " << cust.number << endl;
cout << "Your total bill (including 6% tax): RM" << total_bill << endl;
cout << setfill ('-') << setw (55) << "-" << endl;
cout << endl << "\tPress 1 to return to main screen!";
cout << endl << "\tPress 2 to quit the program!";
char afterpurchase;
afterpurchase=getche();
if (afterpurchase=='1')
{
fclose(fptr);
main();
}
else
exit_system();
}
else if(strcmpi("RETURN",laptop)==0)
main();
else
{
cout << endl << "\tNot available!" << endl;
cout << "\tPress A to try again or B to return to main menu" << endl;
char choice1;
choice1=getche();
choice1=toupper(choice1); // Transform to uppercase
switch (choice1)
{
case 'A': fclose(fptr);
PCPurchase();
break;
default : fclose(fptr);
main();
break;
}
}
}
}
It is because of else statement. If you want to buy the laptop from the second record of the data and so on, it will compare with the first record and will not return true. So, it will proceed to else statement and will not repeat the while loop. Simply change the else statement to make the loop working.

How to change the program to enter the data with spaces while using fstream

void Motherboards::add()
{
char x;
int X;
fstream InFileMB("Motherboard_List.txt", ios::in | ios::out | ios::app);
if (!InFileMB)
{
cerr << "Error: Opening File Failed !!";
}
else
{
MotherBoardEntry:
system("cls");
cout << " Enter the name of the Manufacturer :\n";
string MB__Name_Manufacturer;
cin >> MB__Name_Manufacturer;
cout << " Enter Chipset Type :\n";
string MB_Chip;
cin >> MB_Chip;
cout << "Enter Name of the board exactly as it`s written on the box :\n";
string MB_Name;
cin >> MB_Name;
cout << "Enter 3 features of this board :\n";
cout << "1.) ";
string MB_Feature1;
cin >> MB_Feature1;
cout << endl;
cout << "2.) ";
string MB_Feature2;
cin >> MB_Feature2;
cout << endl;
cout << "3.) ";
string MB_Feature3;
cin >> MB_Feature3;
cout << endl;
cout << "Enter Price :\n";
string MB_Price;
cin >> MB_Price;
system("cls");
cout << "Please check the details before conformation :\n";
cout << "Motherboard :\n";
cout << MB__Name_Manufacturer << endl;
cout << MB_Chip << endl;
cout << MB_Name << endl;
cout << "Features :\n";
cout << "1.) " << MB_Feature1 << endl;
cout << "2.) " << MB_Feature2 << endl;
cout << "3.) " << MB_Feature3 << endl;
cout << "Price :\n";
cout << MB_Price;
cout << "\n\n Do You Want To Add The Following Motherboard To Your Stock List ? (y/n)";
cin >> x;
system("cls");
switch (x)
{
case 'y':
InFileMB << "Motherboard :\n" << MB__Name_Manufacturer << endl << MB_Chip << endl << MB_Name << endl << "Price :\n" << MB_Price << endl << "Features :\n" << "1.) " << MB_Feature1 << endl << "2.) " << MB_Feature2 << endl << "3.) " << MB_Feature3 << endl << endl;
break;
case 'Y':
InFileMB << "Motherboard :\n" << MB__Name_Manufacturer << endl << MB_Chip << endl << MB_Name << endl << "Price :\n" << MB_Price << endl << "Features :\n" << "1.) " << MB_Feature1 << endl << "2.) " << MB_Feature2 << endl << "3.) " << MB_Feature3 << endl << endl;
break;
case 'n':
system("cls");
system("pause,2");
cout << " Enter ( 1 ) to try to enter the data again or ( 2 ) to go back to item selection list .. ";
cin >> X;
switch (X)
{
case 1:
goto MotherBoardEntry;
break;
case 2:
break;
}
break;
case 'N':
system("cls");
system("pause,2");
cout << " Enter ( 1 ) to try enter the data again or ( 2 ) to go back to item selection list .. ";
cin >> X;
switch (X)
{
case 1:
goto MotherBoardEntry;
break;
case 2:
break;
}
break;
}
}
}
When I input the data as I am going to show in the snapshots that I provide when I enter the data without any spaces all goes well but when i do enter the data with spaces i cant fill out certain data due to some reason that I don't know as I am a beginner. Can you please tell me exactly where to update and what to update.
[enter image description here][1]
[enter image description here][2]
As you may have noticed in the picture where i have put a space between i7 and 4790k i couldn`t fill out the information for entering the name of the processor and the command window shifted me directly to the next line.

C++ Simple hangman game [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Hi so i have started c++ 3 days ago, read some tutorials etc. I wanted to make my own hangman game since it seemed as an easy task for a begginer but i stumbled upon an issue. Everything is working well ecept i cant seem to find a way to make 1 letter strings swap with underscores until underscores change to the missing word. So basically when you compile it you can guess the whole word only.
Here is the code:
#include <iostream>
#include <string>
using namespace std;
string player1,player2,word,underscore,guess;
int wrong=0;
int main (){
string copy = word;
cout << "----------------------Hello! Welcome to the HANGMAN game!---------- ----------" << endl;
cout << "Please type in your name, PLAYER 1" << endl;
cin >> player1;
cout << "Please type in your name, PLAYER 2" << endl;
cin >> player2;
cout << "OK " << player1 << " and " << player2 << ". Let's start with the game!" << endl;
cout << player1 << " please input the word you want " << player2 << " to guess." << endl;
cin >> word;
//space
for (int x=0; x<30; x++){
cout << endl;
}
//UNDERSCORE
while (underscore.size() != word.size()){
underscore.push_back('_');}
cout << underscore << endl;
//MAIN WHILE
while(wrong<12){
cin >> guess;
//IF GUESS ISNT LETTER
if(guess.size() > 1){
if(guess==word){
cout << "Thats the right word." << endl;
break;
}
else{
cout << underscore << endl;
cout << "Wrong word try again." << endl;
cout << "Used: " << usedguess << endl;
wrong ++;
}
}
if(underscore == word){
cout << "You win!" << endl;
break;
}
if(wrong==1){
cout << "I" << endl;
}
else if(wrong==2){
cout << "I" << endl;
cout << "I" << endl;
}
else if(wrong==3){
cout << "I" << endl;
cout << "I" << endl;
cout << "I" << endl;
}
else if(wrong==4){
cout << "I" << endl;
cout << "I" << endl;
cout << "I" << endl;
cout << "I" << endl;
}
else if(wrong==5){
cout << "I" << endl;
cout << "I" << endl;
cout << "I" << endl;
cout << "I" << endl;
cout << "I" << endl;
}
else if(wrong==6){
cout << "I===" << endl;
cout << "I" << endl;
cout << "I" << endl;
cout << "I" << endl;
cout << "I" << endl;
}
else if(wrong==7){
cout << "I===" << endl;
cout << "I O" << endl;
cout << "I" << endl;
cout << "I" << endl;
cout << "I" << endl;
}
else if(wrong==8){
cout << "I===" << endl;
cout << "I O" << endl;
cout << "I |" << endl;
cout << "I" << endl;
cout << "I" << endl;
}
else if(wrong==9){
cout << "I===" << endl;
cout << "I O" << endl;
cout << "I -|" << endl;
cout << "I" << endl;
cout << "I" << endl;
}
else if(wrong==10){
cout << "I===" << endl;
cout << "I O" << endl;
cout << "I -|-" << endl;
cout << "I" << endl;
cout << "I" << endl;
}
else if(wrong==11){
cout << "I===" << endl;
cout << "I O" << endl;
cout << "I -|-" << endl;
cout << "I /" << endl;
cout << "I" << endl;
}
else if(wrong==12){
cout << "I===" << endl;
cout << "I O" << endl;
cout << "I -|-" << endl;
cout << "I / /"<< endl;
cout << "I YOU ARE DEAD" << endl;
cout << "Game over bro! The word was: " << word <<endl;
break;
}
}
}
To compare the strings of word and guess, you can iterate over the characters in a for-loop, and check if there is a match
string word = "hangman";
string guess = "mansomething";
string underscore = string(word.size(), '_'); // init a string with underscores equal to the length of 'word'
// iterate over the characters in word and guess
for (size_t i = 0, iend = min(word.size(), guess.size()); i < iend; i++) {
if (word[i] == guess[i])
underscore[i] = word[i]; // if the characters match at position i, update the underscore.
}
cout << underscore << endl;
Afterwards, underscore contains the following
_an____