I need to make the values modifiable - c++

I need to be able to update these variables.
Base Damage
Accuracy
Rate of fire
Range
I need to be able to add to the base damage or accuracy or the rate of fire or the range, once I have already added I need to be able to
continuously update the variable by adding more points to the variable if I so desire to do so.
The points total needs to be subtracted but when the variable is first subtracted if you continue to buy within the menu the variable does not change at all.
Once you have the variables updated you should be able to then look at the total of the points value and the weapon stats and see a changes after repetitive buying.
The variables after 1 purchase continue to remain stagnant.
I am sorry for this large amount of text I am just not sure what to take away from these segments of code.
The main question is how to modify the value of a variable after it had been added or subtracted to.
#include <iostream>
#include <string>
using namespace std;
int i;
int x;
int g;
class shotgun
{
private:
int a = 40, b = 15, c = 10, d = 6, j = 10, p = 10, v = 5, n = 2, o = 5, k = 5;
int pointstotal = p -= v;
int baseDamage = a += j;
int accuracy = b += k;
int range = c += o;
int rateOffire = d += k;
public:
shotgun(){
do {
cout << "You have 10 points at your disposal" << endl;
cout << "Your shotgun stats are.." << endl;
cout << "Base Damage: " << a << endl;
cout << "Accuracy:" << b << endl;
cout << "Range:" << c << endl;
cout << "Rate of Fire:" << d << "s" << endl;
cout << "1)Would you like to choose something that
upgrades your damage output?" << endl;
cout << "2)Would you like something for accuracy?" << endl;
cout << "3)Would you like something for range?" << endl;
cout << "4)Would you like some thing for your rate of fire?" << endl;
cout << "5)Would you like to see your new weapon's stats and your points." << endl;
cout << "6)Would you like to exit the program?" << endl;
cin >> i;
switch (i) {
case 1:
cout << "Here are some slugs for your damage output.." << endl;
a + j;
p - v;
break;
case 2:
cout << "Here is a longer stock for your shotgun." << endl;
b + k;
p - v;
break;
case 3:
cout << "Here is a longer barrel for your shotgun." << endl;
c + o;
p - v;
break;
case 4:
cout << "Here is better break action barrel for your shotgun." << endl;
d + n;
p - v;
break;
case 5:
cout << "You now have" << pointstotal << "points at your disposal." << endl;
cout << "Your shotgun stats are now.." << endl;
cout << "Base Damage:" << baseDamage << endl;
cout << "Accuracy:" << accuracy << endl;
cout << "Range:" << range << endl;
cout << "Rate of Fire:" << rateOffire << "s" << endl;
break;
case 6:
cout << "Exiting Program" << endl;
g = 5;
}
} while (g != 5);
}
};
int main()
{
cout << "Welcome to the weapon customization system!" << endl;
cout << "Choose your Weapon to customize you have ten points" << endl;
cout << "*************************************************" << endl;
cout << "1)Choose the double barreled shotgun?" << endl;
cout << "2)Choose the assault rifle?" << endl;
cout << "3)Choose the 44. Magnum?" << endl;
cout << "4)Choose the combat shotgun?" << endl;
cin >> x;
switch (x)
{
case 1:
shotgun e;
break;
}
cout << "\n\n";
system("Pause");
}
The variables will stay the same even after you have used the previous options to modify the stats within the switch case if you press 5 as an option after upgrading the weapon.

Your problem is here:
switch (x)
{
case 1:
shotgun e;
break;
}
... you're declaring an object of type shotgun inside the case statement, which means that a new shotgun object is created whenever case 1 is entered, and destroyed when that scope is exited (i.e. when the break command is executed).
If you want the state of your shotgun object to persist, you'll need to declare it at an earlier/bigger scope (e.g. at the beginning of main() would be a good spot for it)
Also, the attempted-variable-modifications inside your do...while() loop are wrong; instead of:
case 1:
cout << "Here are some slugs for your damage output.." << endl;
a + j;
p - v;
break;
... you probably meant to do:
case 1:
cout << "Here are some slugs for your damage output.." << endl;
a += j;
p -= v;
break;
.... note the += means "increase by" and the -= means "decrease by" (whereas a+j and p-v merely compute a value that gets immediately discarded, so they have no effect)
As an aside, you should probably move the do...while() loop out of the shotgun constructor and into a separate method that you can call later on; otherwise it will be executed every time a shotgun object is created, which is probably not what you want.

HERE IS THE FINAL RESULT.
I completed this code with the advice given thank you for the advice.
For those who need extra help. :)
#include <iostream>
#include <string>
using namespace std;
int i;
int x;
int g;
int j = 5;
class assaultrifle
{
private:
int baseassaultPoints = 10, baseassaultDamage = 35, baseassaultAccuracy = 56, baseassaultRange = 72, baseassaultROF = 78;
int assaultPoints = 10, assaultDamage = 35, assaultAccuracy = 56, assaultRange = 72, assaultROF = 78;
public:
int v = 5, n = 2, o = 5, k = 5, j = 5;
assaultrifle()
{
do {
cout << "These are your base stats for your gun.." << endl;
cout << "Your weapon has a base damage of:" << baseassaultDamage << endl;
cout << "Your weapon has an accuracy of: " << baseassaultAccuracy << endl;
cout << "Your weapon has a range of:" << baseassaultRange << endl;
cout << "Your weapon has a rate of fire of:" << baseassaultROF << endl;
cout << "**************************************" << endl;
cout << "You have " << assaultPoints << "assaultpoints.." << endl;
cout << "1)Would you like to choose something that upgrades your damage output?" << endl;
cout << "2)Would you like something for accuracy?" << endl;
cout << "3)Would you like something for range?" << endl;
cout << "4)Would you like some thing for your rate of fire?" << endl;
cout << "5)Would you like to exit the program?" << endl;
cin >> i;
system("Pause");
system("cls");
if (assaultPoints == 0) {
cout << "You have" << assaultPoints << "points at your disposal" << endl;
cout << "Your upgraded M16 now has better stats." << endl;
cout << "Your final assault rifle stats are.." << endl;
cout << "Base Damage: " << assaultDamage << endl;
cout << "Accuracy:" << assaultAccuracy << endl;
cout << "Range:" << assaultRange << "meters" << endl;
cout << "Rate of Fire:" << assaultRange << "s" << endl;
cout << "**************************************" << endl;
}
switch (i) {
case 1:
cout << "Here are some armor piercing rounds for your damage output.." << endl;
assaultDamage += j;
assaultPoints -= v;
break;
case 2:
cout << "Here is a foregrip for your assault rifle." << endl;
assaultAccuracy += k;
assaultPoints -= v;
break;
case 3:
cout << "Here is a heavy barrel for your assault rifle." << endl;
assaultRange += o;
assaultPoints -= v;
break;
case 4:
cout << "Here is taped magazine for your assault rifle." << endl;
assaultROF += n;
assaultPoints -= v;
break;
case 5:
cout << "Exiting Program" << endl;
g = 5;
}
} while (g != 5);
}
};
class shotgun {
private:
int baseShotgunDamage = 50, baseShotgunAccuracy = 15, baseShotgunRange = 10, baseShotgunROF = 6, baseShotgunPoints = 10;
int shotgunDam = 50, shotgunAccuracy = 15, shotgunRange = 10, shotgunROF = 6, j = 10, shotgunPoints = 10;
int pointstotal = shotgunPoints - v;
int baseDamage = shotgunDam + j;
int accuracy = shotgunAccuracy + k;
int range = shotgunRange + o;
int rateOffire = shotgunROF + k;
public:
int v = 5, n = 2, o = 5, k = 5;
shotgun()
{
do {
cout << "These are your base stats for your gun.." << endl;
cout << "Your weapon has a base damage of:" << baseShotgunDamage << endl;
cout << "Your weapon has an accuracy of: " << baseShotgunAccuracy << endl;
cout << "Your weapon has a range of:" << baseShotgunRange << endl;
cout << "Your weapon has a rate of fire of:" << baseShotgunROF << endl;
cout << "**************************************" << endl;
cout << "You have " << shotgunPoints << "sawed off shotgun points.." << endl;
cout << "1)Would you like to choose something that upgrades your damage output?" << endl;
cout << "2)Would you like something for accuracy?" << endl;
cout << "3)Would you like something for range?" << endl;
cout << "4)Would you like some thing for your rate of fire?" << endl;
cout << "5)Would you like to exit the program?" << endl;
cout << "**************************************" << endl;
cin >> i;
system("Pause");
system("cls");
if (shotgunPoints == 0) {
cout << "You have" << shotgunPoints << "points at your disposal" << endl;
cout << "Your final double barreled shotgun stats are.." << endl;
cout << "Base Damage: " << shotgunDam << endl;
cout << "Accuracy:" << shotgunAccuracy << endl;
cout << "Range:" << shotgunRange << "meters" << endl;
cout << "Rate of Fire:" << shotgunROF << "s" << endl;
cout << "**************************************" << endl;
}
switch (i) {
case 1:
cout << "Here are some slugs for your damage output.." << endl;
shotgunDam += j;
shotgunPoints -= v;
break;
case 2:
cout << "Here is a longer stock for your shotgun." << endl;
shotgunAccuracy += k;
shotgunPoints -= v;
break;
case 3:
cout << "Here is a longer barrel for your shotgun." << endl;
shotgunRange += o;
shotgunPoints -= v;
break;
case 4:
cout << "Here is better break action barrel for your shotgun." << endl;
shotgunROF += n;
shotgunPoints -= v;
break;
case 5:
cout << "Exiting Program" << endl;
g = 5;
}
} while (g != 5);
}
};
class handgun
{
private:
int basehandgunDam = 15, basehandgunAccuracy = 55, basehandgunRange = 25, basehandgunROF = 19, j = 10, basehandgunPoints = 10;
int handgunDam = 15, handgunAccuracy = 55, handgunRange = 25, handgunROF = 19, handgunPoints = 10;
int pointstotal = handgunPoints - v;
int baseDamage = handgunDam + j;
int accuracy = handgunAccuracy + k;
int range = handgunRange + o;
int rateOffire = handgunROF + k;
public:
int v = 5, n = 2, o = 5, k = 5;
handgun()
{
do {
cout << "These are your base stats for your gun.." << endl;
cout << "Your weapon has a base damage of:" << basehandgunDam << endl;
cout << "Your weapon has an accuracy of: " << basehandgunAccuracy << endl;
cout << "Your weapon has a range of:" << basehandgunRange << endl;
cout << "Your weapon has a rate of fire of:" << basehandgunROF << "s" << endl;
cout << "**************************************" << endl;
cout << "You have " << handgunPoints << "glock points.." << endl;
cout << "1)Would you like to choose something that upgrades your damage output?" << endl;
cout << "2)Would you like something for accuracy?" << endl;
cout << "3)Would you like something for range?" << endl;
cout << "4)Would you like some thing for your rate of fire?" << endl;
cout << "5)Would you like to exit the program?" << endl;
cout << "**************************************" << endl;
cin >> i;
system("Pause");
system("cls");
if (handgunPoints == 0) {
cout << "You have" << handgunPoints << "points at your disposal" << endl;
cout << "Your final Glock 17 stats are.." << endl;
cout << "Base Damage: " << handgunDam << endl;
cout << "Accuracy:" << handgunAccuracy << endl;
cout << "Range:" << handgunRange << "meter" << endl;
cout << "Rate of Fire:" << handgunROF << "s" << endl;
cout << "**************************************" << endl;
}
switch (i) {
case 1:
cout << "Here are some hollow points for your damage output.." << endl;
handgunDam += j;
handgunPoints -= v;
break;
case 2:
cout << "Here is a foldable stock for your pistol." << endl;
handgunAccuracy += k;
handgunPoints -= v;
break;
case 3:
cout << "Here is a longer muzzle for your glock 17." << endl;
handgunRange += o;
handgunRange -= v;
break;
case 4:
cout << "Here is a full auto function for you glock 17." << endl;
handgunROF += n;
handgunROF -= v;
break;
case 5:
cout << "Exiting Program" << endl;
g = 5;
}
} while (g != 5);
}
};
class combatshotgun
{
private:
int basecombatDam = 40, basecombatAccuracy = 55, basecombatRange = 25, basecombatRecoil = 20, j = 10, basecombatPoints = 10;
int combatDam = 40, combatAccuracy = 55, combatRange = 25, combatRecoil = 20, combatPoints = 10;
int pointstotal = combatPoints - v;
int baseDamage = combatDam + j;
int accuracy = combatAccuracy + k;
int range = combatRange + o;
int recoil = combatRecoil + k;
public:
int v = 5, n = 2, o = 5, k = 5;
combatshotgun()
{
do {
cout << "These are your base stats for your gun.." << endl;
cout << "Your weapon has a base damage of:" << basecombatDam << endl;
cout << "Your weapon has an accuracy of: " << basecombatAccuracy << endl;
cout << "Your weapon has a range of:" << basecombatRange << endl;
cout << "Your weapon has a rate of fire of:" << basecombatRecoil << endl;
cout << "**************************************" << endl;
cout << "You have " << combatPoints << "combat shotgun points.." << endl;
cout << "1)Would you like to choose something that upgrades your damage output?" << endl;
cout << "2)Would you like something for accuracy?" << endl;
cout << "3)Would you like something for range?" << endl;
cout << "4)Would you like something for the recoil?" << endl;
cout << "5)Would you like to exit the program?" << endl;
cout << "**************************************" << endl;
cin >> i;
system("Pause");
system("cls");
if (combatPoints == 0) {
cout << "You have" << combatPoints << "points at your disposal" << endl;
cout << "Your final shotgun stats are.." << endl;
cout << "Base Damage: " << combatDam << endl;
cout << "Accuracy:" << combatAccuracy << endl;
cout << "Range:" << combatRange << "meters" << endl;
cout << "Recoil:" << combatRecoil << endl;
cout << "**************************************" << endl;
}
switch (i) {
case 1:
cout << "Here are some dragons breath for your Remington 12 gauge.." << endl;
combatDam += j;
combatPoints -= v;
break;
case 2:
cout << "Here is a longer stock for your Remingonton 12 guage." << endl;
combatAccuracy += k;
combatPoints-= v;
break;
case 3:
cout << "Here is a longer barrel for your Remington." << endl;
combatRange += o;
combatPoints -= v;
break;
case 4:
cout << "Here is a foregrip for your remington 12 gauge." << endl;
combatRecoil -= n;
combatPoints -= v;
break;
case 5:
cout << "Exiting Program" << endl;
g = 5;
}
} while (g != 5);
}
};
int main()
{
cout << "Welcome to the weapon customization system!" << endl;
cout << "Choose your Weapon to customize you have ten points" << endl;
cout << "*************************************************" << endl;
cout << "1)Choose the double barreled shotgun?" << endl;
cout << "2)Choose the M16?" << endl;
cout << "3)Choose the Glock 17?" << endl;
cout << "4)Choose the Remington 12 guage?" << endl;
cout << "**************************************" << endl;
cin >> x;
switch (x)
{
case 1:
shotgun();
break;
case 2:
assaultrifle();
break;
case 3:
handgun();
break;
case 4:
combatshotgun();
break;
}
cout << "\n\n";
system("Pause");
}

Related

C++ Left Center Right Dice Game (Game Loop and connecting vectors/arrays to classes/header files)

So i have to code the dice game LCR for a final prject but am having some trouble. First off, I know the code is sloppy and really redundant, that's why im looking for help. I couldn't figure out how to connect the 'chips' int vector and 'name' array into the player.h file. I basically need help writing methods for the chip passing to make the code less redundant. But another problem of mine is having the game loop until just one person has chips. Thanks for any help or advice.
LeftCenterRight.cpp
#include <iostream>
#include <string>
#include <time.h>
#include "Dice.h"
#include "Player.h"
#include <vector>
#include <algorithm>
using namespace std;
void Player::gameRules()
{
cout << ("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n\n");
cout << ("Left Center Right is a multiplayer dice game");
cout << ("With a minimum of three players.");
cout << ("Dice containing letters L, C, R along\n"
"with dots on the remaining side are rolled each turn");
cout << ("\n-----Each Player starts with three chips-----\n");
cout << (">> For each L rolled, the player must pass one chip to the player to their left\n"
">> For each R rolled, the player must pass one chip to the player to their right\n"
">> For each C rolled, the player must pass a chip into the center pot (out of play)\n"
">> Dots are neutral and require no action");
cout << ("If a player has three or more chips, he/she rolls all three dice\n"
"If a player only has two chips, he/she rolles onlt two dice\n"
"If a player only has one chip, he/she rolls only one die\n"
"If a player is out of chips, he/she is still in the game,\n"
"\tbut does not roll any dice and passes their turn"
"\n\n >>> The last player with chips is the winner <<<");
cout << ("\n\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n");
};
int main()
{
int result = 0;
int currPlayer = 1;
srand((unsigned)time(NULL));
int numPlayers;
cout << "How many players are playing? (Please enter 3 or more): " << endl;
cin >> numPlayers;
if (numPlayers <= 2)
{
while (numPlayers <= 2)
{
cout << "More players needed.";
cout << "How many players are player?: ";
cin >> numPlayers;
}
}
std::string* names = new string[numPlayers]; // getting names and index is seat number
for (int i = 0; i < numPlayers; i++)
{
cout << "Please enter your name player " << i+1 << endl;
cin >> names[i];
std::string playerName = names[i];
}
vector<int>chips[1]; // intial 3 chips
for (int i = 0; i < numPlayers; i++)
{
int InitialChips = 3;
chips->push_back(InitialChips);
}
Player::gameRules();
int sum = 0;
for (int i = 0; i < chips->size(); i++)
{
int num = chips->at(i);
sum+=num;
}
int thePot = 0;
int i = 0;
while (sum > 0)
{
if ( i >=4 )
{
i = 0;
}
string currPlayer = names[i];
int currSeat = i;
cout << "It's " << currPlayer << "'s Turn!" << endl;
cout << "[1] Roll Dice [2] Quit :";
int choice;
cin >> choice;
if (choice == 1)
{
if (chips->at(currSeat) == 0)
{
break;
}
if (chips->at(currSeat) >= 3)
{
for (int k = 0; k <= 3; k++)
{
int outcome = Dice::rollDice();
if (outcome == 1)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == 0)
{
int j = (numPlayers - 1);
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i - 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 2)
{
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
if (i == chips->size())
{
int j = chips->at(0);
int currChips2 = chips->at(0);
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
else
{
int j = i + 1;
int currChips2 = (chips->at(j));
chips->at(j) = (currChips2 + 1);
cout << ">> +1 chip to " << names[j] << endl;
cout << ">> " << names[j] << " now has " << chips->at(j) << " chip(s)" << endl;
break;
}
}
if (outcome == 3)
{
thePot++;
cout << ">> +1 chip to the Center Pot" << endl;
cout << "There are now " << thePot << " chip(s) in the Center Pot " << endl;
int currChips = chips->at(i);
chips->at(i) = (currChips - 1);
cout << ">> -1 chip to " << names[i] << endl;
cout << ">> " << names[i] << " now has " << chips->at(i) << " chip(s)" << endl;
break;
}
else if ((outcome == 4) || (outcome == 5) || (outcome == 6))
{
break;
}
}
}
// ^^basically copied and pasted most of the while loop for the other two numbers of dice to roll^^
// had redundant code for if the player had 2 chips, to roll two dice only ^^
// also redundant code for only one chip, to roll one die. ^^
}
}
else if (choice == 2)
{
break;
}
else
{
cout << ">> Input Error";
cout << "[1] Roll Dice [2] Quit";
cin >> choice;
}
i++;
}
return 0;
}
Dice.h
#pragma once
using namespace std;
class Dice
{
public:
static int rollDice();
static int diceOutcome;
};
int Dice::rollDice()
{
int diceOutcome;
diceOutcome = (rand() % 6) + 1;
switch (diceOutcome)
{
default:
cout << "Error, retry";
case 1:
if (diceOutcome == 1)
{
cout << " --- " << endl;
cout << "You rolled a | L | Move 1 chip left." << endl;
cout << " --- " << endl;
return 1;
}
break;
case 2:
if (diceOutcome == 2)
{
cout << " --- " << endl;
cout << "You rolled a | R | Move 1 chip right." << endl;
cout << " --- " << endl;
return 2;
}
break;
case 3:
if (diceOutcome == 3)
{
cout << " --- " << endl;
cout << "You rolled a | C | Move 1 chip to the center." << endl;
cout << " --- " << endl;
return 3;
}
break;
case 4:
if (diceOutcome == 4)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 5:
if (diceOutcome == 5)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
case 6:
if (diceOutcome == 6)
cout << " --- " << endl;
cout << "You rolled a | * | No action needed." << endl;
cout << " --- " << endl;
return 0;
break;
}
}
To be fair, I'm quite new to programming, but I have been working on this project for days and kept running into conatiner problems and storing the name and chip values independently. So i've tried a lot of different things, probably not correctly though so I'm open to anything.

gotoxy prints wrong in c++

I am making a menu for a store with 4 options; add product, delete product, see table of created products and exit the program.
I finished the option to add products and exit, they both work fine.
Now I have to make the option to see the product table, supposedly I had already finished it but I noticed a problem ...
The first time I go in to see the product table, it prints it to me normally, like this.
enter image description here
But when I go to the menu and go back to the product table, it prints it like this.
enter image description here
Like I said, it only prints it right the first time I see it, then it prints it wrong.
Do you know how I can solve it?
This is the part of the code where I print the product table.
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
This is my complete code (maybe I have one or another library too many because I have been experimenting).
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 7;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 4;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
Thank you very much in advance :)
The main reason for this problem is that after the size of the console changes, the position of the symbols you draw has also changed. At the same time, the line break determined by cout<<endl; also has a problem. For example, after the window becomes larger, the line length of the console becomes larger, but cout<<endl; is still the original line length.
However, there is no good solution. I suggest you directly set the console size and m=5, m=m+2.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string>
#include<ctype.h>
#include <stdio.h>
#include <windows.h>
#include<iomanip>
using namespace std;
struct products
{
int numor{},
cant{};
float preuni{},
subt{},
IVA{},
total{};
string cod{};
string descr{};
}product[51];
void add();
void intro_code();
int val_code(char codigo[]);
void table();
void gotoxy(int x, int y);
int i = 1; //Product No. (counter)
int k = 1; //Consecutive number (counter)
int main()
{
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, 1400, 400, TRUE);
char opc;
cout << " Welcome ";
cout << endl;
cout << "\n1.- Add product.";
cout << "\n2.- Delete product.";
cout << "\n3.- Table of created products.";
cout << "\n4.- Exit";
cout << endl;
cout << "\nWhat do you want to do today?: "; cin >> opc;
switch (opc)
{
case '1':
system("cls");
cout << "\nAdd product";
add();
system("pause");
system("cls");
return main();
case '2':
cout << "\nDelete product";
system("cls");
return main();
case '3':
table();
return main();
case '4':
exit(EXIT_SUCCESS);
default:
system("cls");
cout << "Warning: the data entered is not correct, try again.\n\n";
return main();
}
return 0;
}
void add()
{
int can;
cout << "\nHow many products do you want to register?: "; cin >> can;
if (can <= 0 || can > 51)
{
system("cls");
cout << "Warning: The amount of products entered is not valid, try again";
return add();
}
for (int p = 1; p <= can;)
{
if (i < 51)
{
if (k <= 51) // In this part, consecutive numbers are generated automatically
{
cout << "\nNumber of order: ";
cout << k;
cout << endl;
product[i].numor = k;
k++;
}
cin.ignore();
cout << "Name of product: ";
getline(cin, product[i].descr);
intro_code();
cout << "Quantity to sell: "; cin >> product[i].cant;
cout << "unit price: $"; cin >> product[i].preuni;
product[i].subt = product[i].preuni * product[i].cant;
cout << "Subtotal: $" << product[i].subt;
product[i].IVA = product[i].subt * 0.16;
cout << "\nIVA: $" << product[i].IVA;
product[i].total = product[i].subt + product[i].IVA;
cout << "\nTotal price: $" << product[i].total;
cout << "\n-------------------------------------------------------------------------------";
cout << endl;
i++;
}
p++;
}
}
/*In this function the product code is entered, if the user enters a code
less than or greater than 5 characters the program displays an error message and allows the
user try again.*/
void intro_code()
{
char hello[10];
int xyz;
do {
cout << "Code of product (5 digits): ";
cin.getline(hello, 10, '\n');
if (strlen(hello) != 5)
{
cout << "The data entered is incorrect, try again ...";
cout << endl;
return intro_code();
}
else
{
xyz = val_code(hello);
}
} while (xyz == 0);
product[i].cod = hello;
}
/*As the requirement for "product code" is that it does not contain letters, special characters or blank spaces
create the function val_code to go through each character entered in the code, check character by character with the isdigit function
to see if the character is numeric or not, if it is not numeric it prints a warning message and allows the user to try again
without leaving the console.*/
int val_code(char hello[]) {
int abc;
for (abc = 0; abc < strlen(hello); abc++) {
if (!(isdigit(hello[abc]))) {
cout << "The data entered is incorrect, try again ...";
cout << endl;
return 0;
}
}
return 1;
}
void table()
{
int c = k, m = 5;
system("cls");
cout << endl;
cout << "Table of created products";
cout << endl;
cout << endl;
cout << " number of order ";
cout << "| Name of product |";
cout << " Product code |";
cout << " Amount |";
cout << " Unit price |";
cout << " Subtotal |";
cout << " IVA |";
cout << " total price |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
for (int L = 2; L <= c; L++)
{
cout << " ";
cout << "| |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << " |";
cout << endl;
cout << "-------------------------------------------------------------------------------------------------------------------------------------";
cout << endl;
}
for (int h = 1; h < c; h++)
{
gotoxy(8, m);
cout << product[h].numor;
gotoxy(20, m);
cout << product[h].descr;
gotoxy(52, m);
cout << product[h].cod;
gotoxy(70, m);
cout << product[h].cant;
gotoxy(83, m);
cout << "$" << product[h].preuni;
gotoxy(96, m);
cout << "$" << product[h].subt;
gotoxy(107, m);
cout << "$" << product[h].IVA;
gotoxy(119, m);
cout << "$" << product[h].total;
m = m + 2;
}
cout << "\n\n\n";
system("pause");
system("cls");
}
void gotoxy(int x, int y)
{
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
In addition, it is not recommended that you use cmd to make gui.

Making program so that if statement is assigned proper number

I'm trying to making it so that if the planet name is not found in the array, it will set the code variable to -1, but it seems to always make the variable -1 regardless. If I don't have the else statement, the program works fine, but then the switch's default statement doesn't work. How do I make it so that the code variable gets assign the proper value if the planet name is entered incorrectly.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
//declare arrays
string planetNames[8] = { "MERCURY", "VENUS", "EARTH", "MARS", "JUPITER", "SATURN", "URANUS", "NEPTUNE" };
double gravity[8] = { 0.37, 0.78, 1, 0.38, 2.64, 1.16, 1.07, 1.21 };
//declare variable
string name = " ";
double weight = 0.0;
string planet = " ";
double finalWeight = 0.0;
int code = 0;
//explain program to user
cout << "In this program you will enter your first and last name, then your weight, and finally the planet that you want to know your weight on" << endl << endl;
//get input
cout << "What is your first and last name: ";
getline(cin, name);
cout << "How much do you weigh: ";
cin >> weight;
cout << "Which planet would you like to know how much you weigh on: ";
cin >> planet;
//capitalize planet name
transform(planet.begin(), planet.end(), planet.begin(), toupper);
while (weight != -1)
{
for (int x = 0; x < 8; x++)
{
if (planet == planetNames[x])
code = x; //THIS IS WHERE THE PROBLEM IS!!!!!!!!!
else
code = -1;
//end if
}//end for
//calculate and display weights
switch (code)
{
case 0:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 1:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 2:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 3:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 4:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 5:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 6:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
case 7:
finalWeight = weight * gravity[code];
cout << "The weight of " << name << " on " << planetNames[code] << " would be " << finalWeight << "lbs" << endl;
break;
default:
cout << "Invalid planet name" << endl;
}//end switch
cout << endl;
cout << "How much do you weigh(-1 to end the program): ";
cin >> weight;
cout << "Which planet would you like to know how much you weigh on: ";
cin >> planet;
transform(planet.begin(), planet.end(), planet.begin(), toupper);
}//end while
system("pause");
return 0;
}
You need to break the loop after you have found the matching planet name, otherwise the loop keeps searching, and the next name won't match so code is set to -1.
Also: for efficiency and clarity: set code = -1 before the loop and only set to x on a match:
code = -1;
for (int x = 0; x < 8; x++)
{
if (planet == planetNames[x])
{
code = x; //THIS IS WHERE THE PROBLEM IS!!!!!!!!!
break; // And now it's gone ;-)
}
}
this if is fine.
for example if you type mars, code will get value 3.
But then in next step of loop you will set it again to -1 ;)
Break the loop when result is found.
Advice:
Split this part of code to new function.

While loop and boolean function

Hello guys I'm not an expert on the subject so please excuse my pour skills. I finished my program and it works fine (calculator). The problem is that now I don't know where to locate the while loop in conjunct with the Boolean function to repeat the process once it is done with a task (once the program completes a math operation). Any help, comment or suggestion will be greatly appreciated. Thank you.!!
#include <iostream>
#include <math.h>
#include <cmath>
int main()
{
double a=0.0;
double b=0.0;
double c=0.0;
bool repeat = true;
do {
using namespace std;
int x;
cout << "**********************************" << endl;
cout << "| |" << endl;
cout << "| 0 - Quit |" << endl;
cout << "| 1 - Add |" << endl;
cout << "| 2 - Subtract |" << endl;
cout << "| 3 - Divide |" << endl;
cout << "| 4 - Multiply |" << endl;
cout << "| 5 - Raise X to the power Y |" << endl;
cout << "| 6 - Sine ( x ) |" << endl;
cout << "| 7 - Cosine ( x ) |" << endl;
cout << "| 8 - Tangent ( x ) |" << endl;
cout << "**********************************" << endl;
cout << "Enter a selection, please: " << endl;
cin >> x;
switch (x)
{
{
case 1:
cout << " Enter the first value" <<endl;
cin >> a ;
cout << " Enter second value " << endl;
cin >> b;
c=a+b;
cout << "The addition of " << a << " and "<< b << "is" << c << endl;
break;
bool repeat = true;
}
{
case 2:
cout << " Enter the first value" << endl;
cin >> a ;
cout << " Enter the second value " << endl;
cin >> b;
c=a-b;
cout << "The subtraction of " << a << " and " << b << " is: " << c << endl;
break;
bool repeat = true;
}
{
case 3:
cout << " Enter the first value" <<endl;
cin >> a ;
cout << " Enter the second value " << endl;
cin >> b;
c=a/b;
cout << " The division os " << a << " and " << b << "is" << c << endl;
break;
bool repeat = true;
}
{
case 4:
cout << " Enter the first value" <<endl;
cin >> a ;
cout << " Enter the second value " << endl;
cin >> b;
c=a*b;
cout << " The product of " << a << " times " << b << " is " << c << endl;
break;
bool repeat = true;
}
{
case 5:
cout << " Enter the value to be exponentiated " <<endl;
cin >> a ;
cout << " Enter the exponent" << endl;
cin >> b;
c= pow(a,b);
cout << a << " Rased to the power of " << b << " is: " << c << endl;
break;
bool repeat = true;
}
{
case 6:
cout << " Enter the value that you want the sine to be taken of" <<endl;
cin >> a ;
c=sin(a);
cout << " The sine of " << a << " is: " << c << endl ;
break;
bool repeat = true;
}
{
case 7:
cout << " Enter the value that you want the cosine to be taken of" <<endl;
cin >> a ;
c=cos(a);
cout << " The cosine of " << a << " is: " << c << endl ;
break;
bool repeat = true;
}
{
case 8:
cout << " Enter the value that you want the tangent to be taken of" <<endl;
cin >> a ;
c=tan(a);
cout << " The tangent of " << a << " is: " << c << endl ;
break;
bool repeat = true;
}
{
case 0:
cout << "Ending the program" << endl;
return 0;}
break;
bool repeat = true;
}
} while (repeat = true );
return 0;
}
So here is few moments.
Call
using namespace std;
just believe - is bad idea;
In conditions like if() or while() use operator == instead of =. Because "=" - is assigne operator, and return value depended on success of operation. And "==" is compare operator.
Ow and figure one more missunderstanding. Using bool rezult = true; is wrong. You should use rezult = true; Because every time when you write type specifer you create local variable in context of case, and this don`t affect rezult declared in main
My opinion for your question is little change:
from:
do{
int x;
...
case 0:
cout << "Ending the program" << endl;
return 0;}
break;
bool repeat = true;
}
} while (repeat = true );
to
do{
int x;
...
case 0:
cout << "Ending the program" << endl;
repeat = false;}
break;
}
} while (repeat == true);
and if you need a bit more calculations you can wrapped it to new cicle something like:
while(new_condtion == true) {
do {
...
} while(repeat == true);
//change new_condtion
}
Don't redefine repeat within switch case. This creates a different variable named repeat which, although it has the same name, is not the variable named repeat defined before the loop. This is what you get when you copy a definition of the form bool repeat = true; into multiple places.
The continuation condition for the loop (repeat = true) will also loop forever. Comparison is two = signs, not one.

how to make a continous loop with second while statement

okay here is my code for a game called pig. I having trouble because the code for the computers turn will only got through one time and once the second turn is reached the first line is only printed. is there any soluction to this or am I just screwed?
`int main () {
int humanTurn=0;
int humanTotalScore=0;
int computerTotalScore=0;
int computerTurn=3;
float diceRoll = 0;
int score = 0;
int computerScore = 0;
int answer = 0;
int humanScore = 0;
int pause = 0;
float computerDiceRoll = 0;
srand(time(0));
cout << "Welcome to the game of pig, the first player to reach to 100 wins."<< endl;
cout << "if you roll a one no score will be recorded and your turn will go the computer"<< endl;
cout << " If you choose to hold, the total score accumilated will be recorded" << endl;
while ((humanTotalScore < 100) && (computerTotalScore < 100)) {
cout << endl;
cout << endl;
cout << "press 1 to roll or 2 to save your score: ";
cin >> answer;
for (int i=0; i<1; i++) {
diceRoll = rand() % 6 + 1;
}
if ((diceRoll > 1) && ( answer == 1)){
cout << endl;
cout << endl;
cout << "your current roll is: " << diceRoll << endl;
cout << endl;
cout << endl;
score += diceRoll;
cout << "Score for this turn is: " << score << endl;
cout << "your total score is: " << humanTotalScore << endl;
cout << endl;
cout << endl;
}
else if (answer == 2){
cout << "your score of: " << score << " will be saved" << endl;
humanTotalScore += score;
score = 0;
}
else {
cout << endl;
cout << endl;
cout << "you rolled a ONE. You lose your turn and any points that were with it" <<endl;
cout << endl;
cout << endl;
score = 0;
computerTurn = score;
}
if ((computerTurn == 0) || (answer == 2)){
computerDiceRoll = rand() % 6 + 1;
here is code that is giving me loop problems.
while ((computerDiceRoll > 1)&& (computerScore <= 20)){
if (computerDiceRoll == 1){
computerScore = 0;
computerTurn = 1;
cout << "Computer rolled a ONE, it is now your turn." << endl;
}
computerDiceRoll = rand() % 6 + 1;
cout << endl;
cout << endl;
cout << "computers roll is : " << computerDiceRoll << endl;
cout << endl;
cout << endl;
computerScore += computerDiceRoll;
if (computerScore >20){
computerTotalScore += computerScore;
computerTurn = 1;
}
cout << "computer current score is : " << computerScore << endl;
cout << "computer total score is: " << computerTotalScore << endl;
cout << endl;
cout << endl;
}
}
}
} `