Program wont change array value - arrays

(Win32 console app) Ok so i know its a bit to look at, but ive added as many helpful comments that i could think of, im sort of new to coding so if this is a quick fix i apologize for taking your time, ive searched high and low and cant figure this out. So, it prompts the user for a name, that works, then for a race, that works, but under the display function, it fails to show the updated stats (updated by which race you choose). although sometimes it will work with the hp/maxHP but not att nor def. im not sure if its something to do with the scope or what, ive tried all i know :/ thanks for your time and help :)
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int stats[6] = {1, 10, 10, 1, 0, 0};//life(0), maxHp(1), hp(2), att(3), def(4), gold(5)
void shop();//goes to the shop
void fight();//goes to fighting area
void sleep();//refills hp
void welcome();//establishes name
void display();//hud
void whereTo();//travel selection
void doRace();//establishes name
void human();//race#1
void orc();//race#2
void dwarf();//race#3
string name;//variable for name
//Main
int main()
{
welcome();
doRace();
while(stats[0]==1)
{
whereTo();
cout << stats[1];
system("PAUSE");
}
cout << "If you are reading this, you have DIED!\n";
system("PAUSE");
return 0;
}
void shop()
{
display();
cout << "To-be shoping area.\n";
system("PAUSE");
}
void fight()
{
display();
cout << "To-be fighting area.\n";
system("PAUSE");
}
void sleep()
{
display();
cout << "You rest completely..." << endl;
stats[2] = stats[1];
system("PAUSE");
}
void whereTo()
{
display();
cout << "Where would you like to go?\n\n Shop(1)\n Fight(2)\n Sleep(3)\n";
int place;
cin >> place;
system("CLS");
if(place==1)
{
shop();
}
else if(place==2)
{
fight();
}
else if(place==3)
{
sleep();
}
else
{
cout << "Please enter 1, 2, or 3.";
system("PAUSE");
system("CLS");
whereTo();
}
}
void display()//Header to everything
{
system("CLS");
cout << name << " HP: " << stats[2] << "/" << stats[1] << " Att: " << stats[3] << " Def: " << stats[5] << " Gold:" << stats[5] << endl << endl;
}
void welcome()//runs once, establishes name in beginning
{
cout << "Welcome to my first RPG Program\n\n";
system("PAUSE");
system("CLS");
cout << "Enter your character's name\n\n";
cin >> name;
system("CLS");
}
void doRace()//choosing a race at the start
{
cout << "What Race would you like to be?\n\n\n 1)Human (More Attack and Defense)\n\n 2)Orc (More Hp and Attack)\n\n 3)Dwarf (More HP and Defense)\n\n";
int race;
cin >> race;
if(race==1)
{
human();
cout << "You chose Human!" << endl;
system("PAUSE");
}
else if(race==2)
{
orc();
cout << "You chose Orc!" << endl;
system("PAUSE");
}
else if(race==3)
{
dwarf();
cout << "You chose Dwarf!" << endl;
system("PAUSE");
}
else
{
cout << "Please enter 1, 2, or 3.";
system("pause");
system("CLS");
doRace();
}
}
void dwarf()//sets the initial stats of the character based off of race selection
{
stats[1] = stats[1] + 3;//maxHp
stats[2] = stats[2] + 3;//hp
stats[4] = stats[4] + 2;//def
}
void human()//sets the initial stats of the character based off of race selection
{
stats[3] = stats[3] + 2;//att
stats[4] = stats[4] + 2;//def
}
void orc()//sets the initial stats of the character based off of race selection
{
stats[1] = stats[1] + 3;//maxHp
stats[2] = stats[2] + 3;//hp
stats[3] = stats[3] + 2;//att
}

You are using the wrong index for def. It should be 4
Def: " << stats[5].

Related

if loop inside a void function not working

So I'm doing a program for a class, and I set up an if loop inside a function definition to set parameters for entries. I'm supposed to be taking inputs between 0 and 10 only. But it's only catching the numbers that are less than 0. It won't catch the numbers larger than 10.
int main()
{
float score1, score2, score3, score4, score5;
cout << endl;
cout << "Judge #1: " << endl;
getJudgeData(score1);
cout << "Judge #2: " << endl;
getJudgeData(score2);
cout << "Judge #3: " << endl;
getJudgeData(score3);
cout << "Score #4: " << endl;
getJudgeData(score4);
cout << "Score #5: " << endl;
getJudgeData(score5);
calcScore(score1, score2, score3, score4, score5);
return 0;
}
void getJudgeData (float &score)
{
cin >> score;
if(score < 0 || score > 10)
{
cout << "Error: Please enter a score between 0 and 10." << endl;
cin >> score;
}
}
Please change the if condition in your getJudgeData function into a while loop:
void getJudgeData (float &score)
{
cin >> score;
while (score < 0 || score > 10)
{
cout << "Error: Please enter a score between 0 and 10." << endl;
cin >> score;
}
}
Otherwise the condition will be only checked once, means for the first input of every judge. This isn't intended, if I understood your issue correctly.
Please find more information regarding the while loop here:
while

check order of array in c, using recursion and malloc [duplicate]

I am trying to debug a recursive function used to validate user input and return a value when the input is OK. The function looks like this:
double load_price()
{
double price;
Goods * tempGd = new Goods();
cin >> price;
while (!cin)
{
cin.clear();
#undef max
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "You didn't enter a number. Do so, please: ";
cin >> price;
} // endwhile
if (!tempGd->set_price(price))
{
cout << endl;
cout << "The price " << red << "must not" << white << " be negative." << endl;
cout << "Please, insert a new price: ";
load_price();
}
else
{
delete tempGd;
return price;
}
}
The method set_price() of Goods class looks as follows
bool Goods::set_price(double price)
{
if (price> 0)
{
priceSingle_ = price;
priceTotal_ = price* amount_;
return true;
}
return false;
}
I tried drawing the problem on a paper but all my diagrams seem to look the way my function already looks like. I think there are some problems with returns, but I do not know where.
Help would be greatly appreciated.
You're not using the return value of the recursive call. You need to do:
return load_price();
Who talked you into using recursion for that problem?
#undef max
double load_price()
{
for(;;) {
double price;
cin >> price;
if (!cin)
{
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "You didn't enter a number. Do so, please: ";
continue;
}
if (!Goods().set_price(price))
{
cout << endl;
cout << "The price " << red << "must not" << white << " be negative." << endl;
cout << "Please, insert a new price: ";
continue;
}
return price;
}
}

Constructor Operator << Device and Test Dynamic Array

#include iostream
#include cmath
#include fstream
#include cstdlib
#include string
using namespace std;
class Device {//Input and store Device Description and Serial Numbers
protected:
static string serial_number;
static string device_description;
public:
Device() {
serial_number = ("6DCMQ32");
device_description = ("TheDell");
}
Device(string s, string d) {
serial_number = s;
device_description = d;
}
};
string Device::device_description;
string Device::serial_number;
class Test {//Input and store Test Description, recent day, and month;
Calculate the next day
protected:
static string Test_Description;
static int recent_month, recent_day, recent_year, new_month;
static int nmonth, next_month, next_day, next_year, max_day;
public:
Test() {
Test_Description = ("Virtual");
}
static void getMonth() {//Calculates the next/new month
next_month = recent_month + nmonth;
new_month = next_month % 12;
if (next_month >= 12) {
cout << "The next Date: " << new_month << " / ";
}
else {
cout << "The next Date: " << next_month << " / ";
}
}
static void getDay() { //Calculates day of next month
if (new_month == 4 || new_month == 6 || new_month == 9 || new_month == 11) {
max_day = 30;
}
else if (new_month == 2) {
max_day = 29;
}
else {
max_day = 31;
}
if (recent_day > max_day) {
cout << max_day << " / ";
}
else {
cout << recent_day << " / ";
}
}
static void getYear() {// Calculate the year of next month
next_year = recent_year + next_month;
if (next_year >= 12) {
cout << recent_year + (next_month / 12) << endl;
}
else {
cout << next_year << endl;
}
}
static void getDate() {// Collects the output of each element of next date
Test::getMonth(), Test::getDay(), Test::getYear();
}
};
string Test::Test_Description;
int Test::recent_month;
int Test::recent_day;
int Test::recent_year;
int Test::new_month;
int Test::nmonth;
int Test::next_month;
int Test::next_day;
int Test::next_year;
int Test::max_day;
class Lab : public Device, public Test {
protected:
static int n;
public:
friend istream & operator>>(istream & in, Lab & lab) {// Inputs
cout << "Enter Device Desciption and Serial Number: ";
getline(in, device_description);
getline(in, serial_number);
cout << "Enter Test Desciption: ";
getline(in, Test_Description);
cout << "Enter the Number of months: ";
in >> nmonth;
cout << "Enter the Most Recent Date(mm/dd/yyyy): ";
in >> recent_month >> recent_day >> recent_year;
return in;
}
friend ostream & operator<<(ostream & out, Lab & lab) {//Outputs
everything in Device Class
out << Lab::device_description << endl;
out << Lab::serial_number << endl;
out << Lab::Test_Description << endl;
getDate();
return out;
}
static void getN() {
cout << "Enter the number of devices: ";
cin >> n;
}
static void getWrite() {
Lab *obj = new Lab[n];
if (obj == 0) {
cout << "Memory Error";
exit(1);
}
for (int i = 0; i<n; i++) {
cin >> obj[i];
cout << endl;
}
ofstream myfile("Device.txt");
myfile.write((char *)obj, n * sizeof(Lab));
delete[] obj;
}
static void getRead() {
ifstream file2("Device.txt");
Lab *obj2 = new Lab[n];
if (obj2 == 0) {
cout << "Memory Error";
exit(1);
}
file2.read((char *)obj2, n * sizeof(Lab));
for (int i = 0; i < n; i++) {
cout << obj2[i];
cout << endl;
}
delete[] obj2;
}
/*void getSearch(){
}*/
};
int Lab::n;
void main() {
Lab L;
L.getN();
L.getWrite();
L.getRead();
system("pause");
}
The Output I get is TheDell 6DCMQ32, Virtual when I entered my inputs. The date is correct the only problem is the Device Description, Serial Number, and Test Device.
Problem with Operator << in File i/o reading where it outputs the values in the Constructor
Purpose: is to enter the number of months for the next test date of device with input of serial number,
Device Description, Test Description, recent date, and the number of months of two tests. At the end the
program must be searched by having the user to input the serial number and the next date, if these two are
valid everything in the device is listed out.
Short of writing your application, I will do my best to give you some direction.
#include <iostream> // Note the '<' and '>' this is to specify is a language provided include
// More includes with the same issue...
using namespace std; // this is general considered bad=practice see https://stackoverflow.com/a/1452738/8480874 for details
//Input and store Device Description and Serial Numbers
class Device
{ // Notice the white space makes it easier to read...
protected:
//static string serial_number; // declaring this static means _EVERY_ device will have the same serial number
//static string device_description; // same as above
string serialNumber;
string deviceDesc;
public:
Device() : serialNumber("6DCMQ32"), deviceDesc("TheDell")
{
//serial_number = ("6DCMQ32"); // Not the best place for initialization
//device_description = ("TheDell"); // Not the best place for initialization
}
//Device(string s, string d) // you never actually use this
//{
// serial_number = s;
// device_description = d;
//}
};
//string Device::device_description; // This is a sign that you variable will be shared between everyone - not required if you remove the static
//string Device::serial_number; // This is a sign that you variable will be shared between everyone - not required if you remove the static
// This suffers from the same probles as the `class device` above
class Test
{
// Lots of stuff was here just trying to short the answer....
// Mostly has the same culprits mentions for the device
// This is one of the fucntions which gets called when you are trying to "save" the info to a file
static void getMonth(/* ostream & out */) // you need this as a paramater
{
next_month = recent_month + nmonth;
new_month = next_month % 12;
if (next_month >= 12)
{
// This function has no idea is needs to redirect the out put to a file...
// its only outputting to the standard console
cout << "The next Date: " << new_month << " / ";
}
else
{
//cout << "The next Date: " << next_month << " / ";
// using the new parameter in comments
// you can now save to your file
out << /*"The next Date: " <<*/ next_month << " / "; // no I comment out your extra message since you file reading does not look for that
}
}
};
// Again we have the same general misuse of C++ ( please keep learning! hopefully I am point you in the right direction )
class Lab : public Device, public Test
{
protected:
static int n;
public:
friend istream & operator>>(istream & in, Lab & lab)
{
// Inputs
cout << "Enter Device Desciption and Serial Number: ";
getline(in, device_description);
getline(in, serial_number);
cout << "Enter Test Desciption: ";
getline(in, Test_Description);
cout << "Enter the Number of months: ";
in >> nmonth;
cout << "Enter the Most Recent Date(mm/dd/yyyy): ";
in >> recent_month >> recent_day >> recent_year;
return in;
}
friend ostream & operator<<(ostream & out, Lab & lab) {//Outputs
everything in Device Class
out << Lab::device_description << endl;
out << Lab::serial_number << endl;
out << Lab::Test_Description << endl;
// Here you should pass the output pipe
getDate(/* out */);
return out;
}
static void getN() {
cout << "Enter the number of devices: ";
cin >> n;
}
static void getWrite()
{
// there's no real need to be using a pointer or memory allocation
//Lab *obj = new Lab[n];
// you can simply use
Lab obj[n];
//if (obj == 0)
//{
// cout << "Memory Error";
// exit(1);
//}
for (int i = 0; i < n; i++)
{
cin >> obj[i];
cout << endl;
}
ofstream myfile("Device.txt");
//myfile.write((char *)obj, n * sizeof(Lab)); // I've never tried writting an object's memory as a char* to file
// usually I like to generate a human readable output
std::string objBuffer = obj.getSaveBuffer(); // you will need to implement this `getSaveBuffer()` functions
myfile << objBuffer; // This can save lots of different value types for you! see http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/
//delete[] obj; // since there is no more new; we dont need a delete!
}
// The logic of what you read suffers the same general issues as the write.
// Also what/how you read is very far from the save so I can't venture into any solutions
// I'm hoping this will kick start you to figuring it out on your own =)
static void getRead() {
ifstream file2("Device.txt");
Lab *obj2 = new Lab[n];
if (obj2 == 0) {
cout << "Memory Error";
exit(1);
}
file2.read((char *)obj2, n * sizeof(Lab));
for (int i = 0; i < n; i++) {
cout << obj2[i];
cout << endl;
}
delete[] obj2;
}
/*void getSearch(){
}*/
};
int Lab::n;
// A program that runs should always return a numeric result indicating success or failure
//void main() {
int main()
{
Lab L; // Since everything in all your classes is static this didnt really add anything
// you done need an object if the object contains nothing
L.getN();
L.getWrite();
L.getRead();
system("pause"); // this is also bad practice, see https://stackoverflow.com/a/1107717/8480874
// I personally like `getchar()` because it's easy and quick
}

On the output in the for loop it is displaying zero and not accepting the input I cannot figure out what i am doing wrong here

#include <iostream>
#include <exception>
using namespace std;
class Inventory{
friend istream& operator>>(istream&, Inventory);
friend ostream& operator<<(ostream&, Inventory);
private:
int stock;
int quant;
int price;
public:
Inventory(int=0,int=0,double=0);
};
Inventory::Inventory(int s, int q, double p){
stock=s;
quant=q;
price=p;
}
istream& operator>>(istream& in, Inventory){
int s;
int q;
double p;
cout << "Enter stock number: ";
in >> s;
cout << "Enter quantity: ";
in >> q;
cout << "Enter price: ";
in >>p;
Inventory inv(s,q,p);
return in;
}
ostream& operator<<(ostream& out, Inventory inv){
out << "The stock number is: " << inv.stock << endl << "The quantity is: " <<
inv.quant << endl << "The price is: " << inv.price << endl;
return out;
}
int main()
{
Inventory inv[5]={};
for(int i = 0; i <5; i++){
cin >> inv[i];
}
cout<<"------------------------" << endl;
for(int i=0;i<5;i++){
cout<<inv[i];
cout<<"------------------------" << endl;
}
return 0;
}
I can not figure out why when I use the overloaded << operator in the for loop it is displaying zero's, am I not storing the price, quantity and price to the object array correctly? I have tried not using a contructor and using one it did not make a difference, any ideas why the integers and double are not storing to the array?
Your were close! See my // change here comment markers (there are several) in the code below.
The 0's had nothing to do with the << overload, but rather the >> overload.
The deal is that you can use the 'in' istream to input directly to the class variables (without trying to call some other function, or a need for extra variables) in the >> overload, but you need to pass an Inventory reference to do so.
I was surprised that there was no error trying to set primitives to 0 in the constructor parameters?? (I'm likely very 'rusty' on newer C++ handling, been over 15+ years for me), but anyway:
#include <iostream>
#include <exception>
using namespace std;
class Inventory{
friend istream& operator>>(istream&, Inventory&); // change here (Inventory reference)
friend ostream& operator<<(ostream&, Inventory);
private:
int stock;
int quant;
double price; // change here
public:
Inventory(int,int,double); // change here
};
Inventory::Inventory(int s = 0, int q = 0, double p = 0){ // change here
stock=s;
quant=q;
price=p;
}
istream& operator>>(istream& in, Inventory& inv){ // change here (inventory reference)
// change here (removed variables)
cout << "Enter stock number: ";
in >> inv.stock; // change here
cout << "Enter quantity: ";
in >> inv.quant; // change here
cout << "Enter price: ";
in >> inv.price; // change here
// change here (removed function call)
return in;
}
ostream& operator<<(ostream& out, Inventory inv){
out << "The stock number is: " << inv.stock << endl << "The quantity is: " <<
inv.quant << endl << "The price is: " << inv.price << endl;
return out;
}
int main()
{
const int ITEMS = 5; // change here (constant to replace hard-coded value)
Inventory inv[ITEMS]={}; // change here (use the constant)
for(int i = 0; i <ITEMS; i++){ // change here (use the constant)
cin >> inv[i];
}
cout<<"------------------------" << endl;
for(int i=0;i<ITEMS;i++){ // change here (use the constant)
cout<<inv[i];
cout<<"------------------------" << endl;
}
return 0;
}
Give that a run and see how it goes:
Here's my example output when I changed the constant (my change inside the main function) to 2 for a basic test run:
Enter stock number: 123
Enter quantity: 4
Enter price: 2.1
Enter stock number: 467
Enter quantity: 1
Enter price: 1.2
------------------------
The stock number is: 123
The quantity is: 4
The price is: 2.1
------------------------
The stock number is: 467
The quantity is: 1
The price is: 1.2
------------------------

C++ How to Increment Int Variable From String Array Element

I'm wondering if there is a way to increment an int variable when a specific string array element is called? I'm working on a project for fun and have run into a roadblock. The goal of my project is to have a program that determines what genres of electronic music the user likes. The program will present two DJ's and ask the user which one they prefer or allow them to select neither. Each DJ will have up to three genres that they mainly specialize in, and I have created int variables for each (with all being set to 0). Once a user selects a DJ, I want points to be assigned to each genre variable in which the DJ is associated with. I'm unsure of how to set up this rule as everything I have attempted so far has failed (two example attempts are commented out in the code). Eventually my plan is to develop logic to have the DJ's randomly selected, however I need to have the genre tally allocation set up first. Is there any way this can be done? Any help would be greatly appreciated. Cheers!
###include "stdafx.h"
###include < iostream>
###include < iomanip>
###include < string>
###include < array>
###using namespace std;
int main()
{
cout << "Hello! This program is designed to figure out what Electronic Music you like based on artists presented and the answers you choose...\n" << endl;
cout << "When you are ready to begin press \"Enter\"..." << endl;
getchar();
int bigRoom = 0;
int deepHouse = 0;
int drumBass = 0;
int dubstep = 0;
int electroHouse = 0;
int futureHouse = 0;
int hardDance = 0;
int house = 0;
int progressiveHouse = 0;
int techno = 0;
int trance = 0;
int trap = 0;
string textArray[5]{ "DeadMau5", "Armin Van Buuren", "Avicii", "Ferry Corsten", "Kaskade"};
string answer;
cout << "Select the DJ you prefer by number. Otherwise select 3 if you don't know them. " << endl; //Haven't coded option 3 yet.
cout << "1 - " << textArray[1] << endl;
cout << "2 - " << textArray[2] << endl;
cin >> answer;
/*
if (textArray[1]) {
++trance;
}
for (textArray[1]) {
++trance;
}
*/
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
}
//cout << trance << endl;
}
You can increment each tally once the user has selected a DJ:
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
++trance;
// ++ ohter genres you want to increment
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
++trance;
// ++ ohter genres you want to increment
}

Resources