trouble with friend function [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
so my program is that i want the user to enter information about a board so everything is working except the part where i need the user to enter the value of attitude then add another number to increase that attitude so I'm stuck at this. As you can see I declared this function as a friend but when I enter the number that I need to increase it to the value of attitude) it stays the same! I hope I made clear the problem I'm facing! and I'd appreciate some help
#ifndef BOARD_H
#define BOARD_H
class Board {
friend void incAttitude(Board &);
public:
friend void incAttitude(Board &);
static int boardcount;
Board(int=5,int=3,double=1.5,char* ='\0');
~Board();
Board &setBoard(int,int,double,char*);
char getLocation();
Board &print();
double surface();
private:
const int length;
int width;
double attitude;
char location[30];
};
#endif
#include<iostream>
#include<cstring>
#include<string>
#include<assert.h>
using namespace std;
#include "Board.h"
int Board::boardcount=0;
Board::Board(int l,int w,double a,char* lo)
: length(l)
{
width=w;
attitude=a;
location[0]='\0';
boardcount++;
}
Board::~Board(){
boardcount--;
}
Board &Board::setBoard(int l,int w,double a,char* lo)
{
width=(w>=2 && w<=5)?w:3;
attitude=(a>=1.5 && a<=2.8)?a:1.5;
strncpy_s(location,lo,29);
location[29]='\0';
return *this;
}
char Board::getLocation(){
return *location;
}
double Board::surface(){
return length*width;
}
void incAttitude(Board &h)
{
double incAttitude;
cout<<"enter to increase attitude "<<endl;
cin>>incAttitude;
h.attitude+=incAttitude;
cout<<"the attitude of the board after the increase : "<<h.attitude<<endl;
}
Board &Board::print(){
cout<<"the length of the boarad : "<<length<<endl;
cout<<"the width of the board : "<<width<<endl;
cout<<"the height of the board : "<<attitude<<endl;
cout<<"the location of the board : "<<location<<endl;
cout<<"the surface of the board : "<<surface()<<endl;
return *this;
}
int main(){
Board hh;
Board *boardptr;
int count,len,wid;
double att;
char locat[30];
cout<<"how many boards do you need to create ? "<<endl;
cin>>count;
boardptr = new Board[count];
assert(boardptr!=0);
for (int i=0; i<count; i++){
cout << "Enter the length: ";
cin >>len;
cout << "Enter the width: ";
cin >> wid;
cout << "Enter the attitude: ";
cin >> att;
incAttitude(hh);
cout<<"Enter the location: ";
cin >>locat;
boardptr[i].setBoard(len,wid,att,locat);
cout<<"------------------------------------------"<<endl;
if (strcmp("NewYork",locat) == 0)
{
boardptr[i].setBoard(len,wid,att,locat).print();
}
}
delete [] boardptr;
system("pause");
return 0;
}

You have an array of Boards, which is called boardptr. But then what is hh? A single board. What does it do? Nothing! But you are using it in incAttitude(hh);! It does increase the altitude, but not on the board boardptr[i] (that you are using), rather on hh.
Secondly, you are never setting att, which means the altitude is always 1.5 (that's the default value). So incAttitude adds the number to 1.5. You could pass att to incAttitude for example.
Then if your comparison condition, why do you set the board again? It resets every value the user chose. You don't need to, because you already call setBoard a few lines early. The data you set with setBoard is saved in that array, so you don't need to override the data with the exact same data. Just use boardptr[i].print().
char arrays, strcmp, raw pointers and fixed size arrays are from C, you should consider the alternatives:
Char arrays -> std::string
strcmp -> if (str == "foo")
Raw pointers -> Smart pointers (or in your case (because they are used as arrays) std::array or std::vector - std::vector for dynamic size arrays)
Fixed size arrays -> std::array

Related

C++ code compiles but doesn't run [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am currently writing a Texas Hold'em code in order to learn more about c++ and gain experience. But I recently ran into a problem in which I have no idea what to do.My code compiles just fine without errors but once I make it run and it arrive at a specific function it just stops working (as in I get an error from CodeBlock saying your program has stopped working). I have tried cutting out parts such as loops in the function to see which specific part is the problem but after a couple of days im still at a stop.
Here is the function and class that I believe is the problem:
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
Here is the full code in case I am wrong of the source of the problem:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
using namespace std;
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
public:
void set_name(string a){name=a;}
string print_name(){return name;}
void card_generator();
string set_cards(int c){return cards[c];}
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
cin>>i;
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
player[0].card_generator();
max_i = i;//max_i is nb of players
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
int p=0,k;
while(p<6){
k=0;
final_card[0][k]=tempCards[p];
k++;
p++;
}
while(p<12){
k=0;
final_card[1][k]=tempCards[p];
k++;
p++;
}
while(p<17){
k=0;
table_cards[k]=tempCards[p];
k++;
p++;
}
}
void Player::card_generator(){
string card_value[13];
card_value[0]="1";
card_value[1]="2";
card_value[2]="3";
card_value[3]="4";
card_value[4]="5";
card_value[5]="6";
card_value[6]="7";
card_value[7]="8";
card_value[8]="9";
card_value[9]="10";
card_value[10]="J";
card_value[11]="Q";
card_value[12]="K";
string card_type[4];
card_type[0]="of hearts";
card_type[1]="of diamonds";
card_type[2]="of clubs";
card_type[3]="of spades";
string card[53];
int x=0;
fill_n(card,53,0);
for (int j=0;j<4;j++){
for (int q=0;q<13;q++){
card[x]=card_value[q]+" "+card_type[j];
cards[x]=card[x];
x++;
}
}
}
If you have any criticism about the code itself even if not directly linked to problem feel free to tell me as I'm doing this to learn :D. Thank you in advance!!
#include <iostream>
#include <string>
#include <stdlib.h>
#include <ctime>
Be consistent in what you do. Including <stdlib.h> and <ctime> looks strange. Either include <cstdlib> and <ctime>, or include <stdlib.h> and <time.h>.
using namespace std;
Don't do this. This using imports all names from the std namespace, which is several hundreds. Only import those names that you actually need, or, alternatively, write std::time instead of the unqualified time. This makes it perfectly clear that you are referring to the time from the standard library instead of one that you might have defined yourself.
class Player{
string name;
int bank=100;
static string cards[53];
static string final_card[2][6];
static string table_cards[5];
The cards should not be represented as strings, but as a separate data type called Card, with properties like suit and rank and a to_string method.
public:
void set_name(string a){name=a;}
To make your program fast, pass a as const std::string & instead of a simple string. This will prevent some copying of data. You should give a better name to the parameter, e.g. void set_name(const std::string &name) { this.name = name; }.
string print_name(){return name;}
This method does not print anything, therefore it must not be called print_name.
void card_generator();
Methods usually are named with verbs, not with nouns. So generate_cards would be a better name. But what does generate mean here? (I'm not a native English speaker, but would draw_cards describe it accurately?)
string set_cards(int c){return cards[c];}
A method called set_* usually modifies something. This one doesn't. Why did you name it this way?
int print_bank(){return bank;}
void set_final_card(int i, int max_i);
Give better names to the parameters. From reading only this declaration, I have no idea what i and max_i might mean.
void print_cards(){for(int i=0;i<6;i++){cout<<final_card[0][i]<<endl;}}
};
string Player::cards[53];
string Player::final_card[2][6];
string Player::table_cards[5];
It looks strange that the cards are stored in the Player class, since no poker player should ever have insight to all 52 cards. And why 53? Is there a joker in your game? These three fields should be moved to a class Table. This allows you to have multiple independent tables, which is nice for a big tournament.
int main () {
int choice1=0, i, max_i, tempV;
string username;
cout<< "Welcome to Texas Hold'Em!\n1-Play\n2-Quit\n";//menu
while((choice1!=1)&&(choice1!=2)){//Makes sure that user enters correct input```
Before reading the choice1 variable, you must initialize it. Since you don't do it, you invoke undefined behavior and everything that the program does after that is unpredictable.
cin>>choice1;
if ((choice1!=1)&&(choice1!=2)){
cout<<"Invalid Input!\nTry again!\n";
}
}
system ("cls");
if (choice1==2){//End Program
return 0;
}
cout<<"How many players?[2-6]"<<endl;
while((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){//Makes sure that user enters correct input
Same here. The user hasn't yet entered anything, so how can you check it?
cin>>i;
Add error handling for every input by enclosing it in an if clause: if (std::cin >> i) {.
if ((i!=2)&&(i!=3)&&(i!=4)&&(i!=5)&&(i!=6)){
cout<<"Invalid Input!\nTry again!\n";
}
}
Player player[i];//creating array of players
Don't use arrays, use a std::vector instead. This allows you to easily extend the table to have 10 players. In the end, there should not be a single 6 in your program.
player[0].card_generator();
max_i = i;//max_i is nb of players
Why do you call this variable max_i, when the comment says that max_players would be a better name?
i--;//since arrays start at 0
system("cls");
player[0].set_final_card(i,max_i);
player[0].print_cards();
if (choice1==1) {//SET NAMES OF ALL PLAYERS
for(i=0; i<max_i; i++){
cout<< "Whats your name?\n";
cin>>username;
player[i].set_name(username);
cout<<"Your name is "<< player[i].print_name()<< " and you have "<< player[i].print_bank()<<"$\n";
tempV=i+1;//used bc arrays start at 0
if(tempV!=max_i){
What does the V in tempV mean?
cout<< "Give PC to player "<< i+2 <<endl;
}
_sleep(3000);
system("cls");
}
}
return 0;
}
void Player::set_final_card(int i, int max_i){
srand(time(NULL));
int tempV = 17;//create temp cards
This 17 is a magic number. It would be better to write it as 5 + 6 * 2, since that makes it much clearer.
string tempCards[tempV];
int randNB[tempV];
int check1 = 0, tmp;
while (check1==0){
for(int g=0; g<tempV;g++){
tempCards[g]=cards[rand()%53];
The 53 is wrong here. I can only be wrong. When you select from 52 cards with equal probability, it must be % 52.
check1=1;
tmp = g - 1;
for(int o=tmp; o!=0; o--){
if (tempCards[g]==tempCards[o]){
check1=0;
}
}
}
}
Captain Giraffe has answered this question in the comments. If any newbies like me face a similar problem look up what a debugger is, as errors like these are called run-time errors. Check this page for a simple explanation: http://www.cplusplus.com/forum/articles/28767/ .

c++ Not able to add an element in the array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am fairly new to c++. I am trying to add another element in the array. The function should change the array and the number of items in the array after the addEntry function is completed, but it doesn't. If I use the display function to show the array, only the original array is shown. Please help.
#include<iostream>
#include<string>
using namespace std;
const int MAXSIZE = 10; // total size of array
void display(string[], int);
void addEntry(string[], int&);
int main()
{
string name[MAXSIZE] = {"raj","casey","tom","phil"};
int numEntries = 4; // number of elements in the array
string choice; // the user choice to add an element or display or exit
cout<<numEntries<<" names were read in."<<endl;
do
{
cout<<endl<<"Enter menu choice (display, add, quit): ";
getline(cin,choice);
if (choice == "display")
{
display(name, numEntries);
cout<<endl;
}
else if (choice == "add")
{
addEntry(name, numEntries);
cout<<endl;
}
else
{
cout<<"bye"<<endl;
}
} while (choice!="quit");
system ("pause");
return 0;
}
void display(string name[], int numEntries)
{
for (int i = 0; i < numEntries; i++)
{
cout<<name[i]<<endl;
}
return;
}
void addEntry(string name[], int& numEntries)
{
if (numEntries<MAXSIZE-1)
{
numEntries++;
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries]);
cout << "Entry added.";
return;
}
else
{
cout<<"There is not enough space is in the array to add a new entry!";
return;
}
}
getline(cin,name[numEntries]);
numEntries is the number of valid entries in your array. name[numEntries] is the element that is following the last valid entry. Use name[numEntries-1].
Or even better, use std::vector instead of C arrays, after all, you are writing in C++.
Your program works, you are just pointing the the wrong location in your array in addEntry. Remember that arrays in C++ are 0-based, try incrementing the value of numEntries AFTER inserting the element in your array, for example:
void addEntry(string name[], int& numEntries)
{
if (numEntries<MAXSIZE)
{
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries++]);
cout << "Entry added.";
return;
}
else
{
cout<<"There is not enough space is in the array to add a new entry!";
return;
}
}
The bug in your code is in the following lines:
numEntries++;
cout<<"Enter name of the person to add: ";
getline(cin,name[numEntries]);
You need to increment numEntries after the call to getline. Use:
cout<<"Enter name of the person to add: ";
if ( getline(cin,name[numEntries]) )
{
// Increment only if getline was successful.
numEntries++;
}

Not understanding the error message I'm getting

I doing a freind function program according to this book I have and I did a little of my own code to the program. I puzzle because I get this error message that the "room_num" is undeclared and intellisense identifier "room_num" is undefine. I need help in understanding why this is happen and how to fix it. Here is the code I have been working on for the passed three weeks.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
class HotelRoom
{
friend int Transfer( HotelRoom&, int);
private:
int room_num;
int transroom_num;
int room_cap;
int occup_stat;
double daily_rt;
public:
HotelRoom(int room, int roomcap, int occup, int transroom, double rate = 89.00);
~HotelRoom();
int Display_Number(); //Displays room number and add the method Display_Guest()
int Get_Capacity();
int Get_Status();
double Get_Rate();
int Change_Status(int);
double Change_Rate(double);
void Display_Guest();
};
HotelRoom::~HotelRoom()
{
cout << endl<<endl;
cout << "Guest in room "<<room_num << " has checked out." <<endl;
}
int HotelRoom::Display_Number()
{
return room_num;
}
int HotelRoom::Get_Capacity()
{
return room_cap;
}
int HotelRoom::Get_Status()
{
return occup_stat;
}
int HotelRoom::Change_Status(int occup)
{
occup_stat = occup;
if (occup > room_cap)
{
return -1;
}
else
return occup_stat;
}
double HotelRoom::Get_Rate()
{
return daily_rt;
}
double HotelRoom::Change_Rate(double rate)
{
daily_rt = rate;
return daily_rt;
}
int Transfer(HotelRoom& room_r1, int transroom)
{
//if guest transfers to different hotel room, room is vacant and transroom is now occupied
room_r1.room_num = room_r1.transroom_num;
return room_num;
}
int main()
{
cout<< setprecision(2)
<<setiosflags(ios::fixed)
<<setiosflags(ios::showpoint);
int room = 0;
int roomcap = 4;
int transroom;
int occup;
double rate = 89.00;
cout<<"\nEnter the room number: "<<endl;
cin>>room;
cout<<"\nEnter the amount of guest to occupy this room: "<<endl;
cin>>occup;
cout<<"\nThe guest has decided to transfer rooms"<<endl;
cout<<"\nEnter the room to transfer the guest to"<<endl;
cin>>transroom;
HotelRoom room1(room,roomcap, occup, transroom, rate ); //initialize the object
if (room1.Change_Status(occup) == -1)
{
cout<<"You have exceeded the room capacity"<<endl;
}
else
{
cout <<"\nThe room number is ";
room1.Display_Number();
cout<<"."<<endl;
cout<<"\nThe name of the primary guest is ";
room1.Display_Guest();
cout <<"."<<endl;
cout<<"\nThe number of guest in the room is "<<room1.Change_Status(occup)<<"." <<endl;
cout<<"\nThe daily rate for room "<<room<< " is "<<room1.Get_Rate()<<"."<<endl<<endl;
cout<<"\nYou have tranferred the guest from room"<<room1.Display_Number()<<"to" <<Transfer(room1,transroom)<<endl;
}
cout<<"\nRoom ";
room1.Display_Number();
cout<<" is vacant."<<endl;
system("PAUSE");
return 0;
}
The function Transfer is not a method of HotelRoom, still you are trying to access room_num in it as if it was. You need to specify which room_num of which HotelRoom instance you mean. Probably you meant return room_r1.room_num instead of return room_num.
Also in your Transfer function you never use the parameter transroom, instead you are using a transroom_num from room_r1. This is probably not what you want.
Finally you haven't implemented the constructor and DisplayRoom of HotelRoom. You should create a stubs, which do nothing or print warnings as long as you haven't implemented the methods properly, so you can at least compile and link the code.
Since you are a beginner I would just stick with member functions and class private variables until you get better at it.
As far as the error message, my guess is that inside the function you are using room_num does not have access to the private parts of the HotelRoom class. Notice I said guess, that's because you should copy and paste the text on the output window here so we can see what exactly is happening.
First, you have to identify that room_num is class member variable.
int Transfer(HotelRoom& room_r1, int transroom)
{
room_r1.room_num = room_r1.transroom_num;
//because room_num is not non class member variable, you have to write like below.
return room_r1.room_num;
//return room_num;
}
Secondly, you did not write definition HotelRoom::HotelRoom(int,int,int,int,double), HotelRoom::Display_Guest(void). So you have to write this constructor and function for avoiding error LNK2019.

C++ run error: pointer being freed was not allocated [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm learning c++ and am working on a program that keeps giving me a 'pointer being freed was not allocated' error. It's a grocery store program that inputs data from a txt file, then user can enter item# & qty. I've read through similar questions but what's throwing me off is the 'pointer' issue. I would appreciate if someone could take a look and help me out. I'm using Netbeans IDE 7.2 on a Mac.
I'll just post the whole piece I have so far. Thx.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Product
{
public:
// PLU Code
int getiPluCode()
{
return iPluCode;
}
void setiPluCode( int iTempPluCode)
{
iPluCode = iTempPluCode;
}
// Description
string getsDescription()
{
return sDescription;
}
void setsDescription( string sTempDescription)
{
sDescription = sTempDescription;
}
// Price
double getdPrice()
{
return dPrice;
}
void setdPrice( double dTempPrice)
{
dPrice = dTempPrice;
}
// Type..weight or unit
int getiType()
{
return iType;
}
void setiType( int iTempType)
{
iType = iTempType;
}
// Inventory quantity
double getdInventory()
{
return dInventory;
}
void setdInventory( double dTempInventory)
{
dInventory = dTempInventory;
}
private:
int iPluCode;
string sDescription;
double dPrice;
int iType;
double dInventory;
};
int main ()
{
Product paInventory[21]; // Create inventory array
Product paPurchase[21]; // Create customer purchase array
// Constructor to open inventory input file
ifstream InputInventory ("inventory.txt", ios::in);
//If ifstream could not open the file
if (!InputInventory)
{
cerr << "File could not be opened" << endl;
exit (1);
}//end if
int x = 0;
while (!InputInventory.eof () )
{
int iTempPluCode;
string sTempDescription;
double dTempPrice;
int iTempType;
double dTempInventory;
InputInventory >> iTempPluCode >> sTempDescription >> dTempPrice >> iTempType >> dTempInventory;
paInventory[x].setiPluCode(iTempPluCode);
paInventory[x].setsDescription(sTempDescription);
paInventory[x].setdPrice(dTempPrice);
paInventory[x].setiType(iTempType);
paInventory[x].setdInventory(dTempInventory);
x++;
}
bool bQuit = false;
//CREATE MY TOTAL VARIABLE HERE!
int iUserItemCount = 0;
do
{
int iUserPLUCode;
double dUserAmount;
double dAmountAvailable;
int iProductIndex = -1;
//CREATE MY SUBTOTAL VARIABLE HERE!
while(iProductIndex == -1)
{
cout<<"Please enter the PLU Code of the product."<< endl;
cin>>iUserPLUCode;
for(int i = 0; i < 21; i++)
{
if(iUserPLUCode == paInventory[i].getiPluCode())
{
dAmountAvailable = paInventory[i].getdInventory();
iProductIndex = i;
}
}
//PLU code entry validation
if(iProductIndex == -1)
{
cout << "You have entered an invalid PLU Code.";
}
}
cout<<"Enter the quantity to buy.\n"<< "There are "<< dAmountAvailable << "available.\n";
cin>> dUserAmount;
while(dUserAmount > dAmountAvailable)
{
cout<<"That's too many, please try again";
cin>>dUserAmount;
}
paPurchase[iUserItemCount].setiPluCode(iUserPLUCode);// Array of objects function calls
paPurchase[iUserItemCount].setdInventory(dUserAmount);
paPurchase[iUserItemCount].setdPrice(paInventory[iProductIndex].getdPrice());
paInventory[iProductIndex].setdInventory( paInventory[iProductIndex].getdInventory() - dUserAmount );
iUserItemCount++;
cout <<"Are you done purchasing items? Enter 1 for yes and 0 for no.\n";
cin >> bQuit;
//NOTE: Put Amount * quantity for subtotal
//NOTE: Put code to update subtotal (total += subtotal)
// NOTE: Need to create the output txt file!
}while(!bQuit);
return 0;
}
iUserItemCount is never initialised. You're invoking undefined behaviour when you use it as an index.
Because you work with statically allocated arrays you probably stumbled upon writing after the end of the array.
You state that the file has exactly 21 entries but what happens with the eof condition? If you read the last entry, the stream still doesn't have the eof bit set. This only happens when you try to read and there is nothing.
After the 21st entry, the loop still continues because the eof bit is not set. It reads garbage information and tries to store it into paInventory[21], but the array was only 21 in size.
//after last read x=21 and eof not set
while (!InputInventory.eof () )
{
//first read causes eof to be set
InputInventory >> iTempPluCode >> sTempDescription >> dTempPrice >> iTempType >> dTempInventory;
//Accessing paInventory[21] here which causes your error
paInventory[x].setiPluCode(iTempPluCode);
//...//
}

Parameter Passing Converting Floats error

I'm having an issue with passing parameters for this simple program. I am getting a "cannot convert 'float*' to 'float' argument '2' to 'void getData(std::string, float, float, float, float)'" error when trying to compile this program. Can anyone figure out what I'm doing wrong? I've been trying forever. Note: Please ignore deprecated stuff like system("PAUSE") and a few other things. This is simple the way my teacher has thought me to code and this is what he wants me using for this program. I am aware of getchar() and I use it for practice and final work. Plus this shouldn't affect the program as I have been using it without issues before on small programs for my C++ class.
Here's the code:
#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
void getData(string,float,float,float,float);
void getCalc(int,float,float,float,float,float,float,float,float,float,float);
void getPrint(float,float,float);
int main()
{
int const acres=1000;
string crop;
float cpa[4];
float yield[4];
float per[4];
float increase[4];
float cost[4];
float grossmin[4];
float grossmax[4];
float netmin[4];
float netmax[4];
float netave[4];
getData(crop,cpa,yield,per,increase);
getCalc(acres,cpa,yield,per,increase,cost,grossmin,grossmax,netmin,netmax,netave);
getPrint(netmin,netmax,netave);
system("PAUSE");
return 0;
}
void getData(string fcrop,float fcpa[],float fyield[],float fper[],float fincrease[])
{
for (int i=0;i<4;i++)
{
cout<<"Enter the crop: ";
getline(cin,fcrop);
cout<<"Enter the cost per acre:$ ";
cin>>fcpa[i];
cout<<"Enter the yield: ";
cin>>fyield[i];
cout<<"Enter $/bishell: ";
cin>>fper[i];
cout<<"Enter the percentage increase: ";
cin>>fincrease[i];
cin.ignore(80,'\n');
}
}
void getCalc(int acres,float fcpa[],float fyield[],float fper[],float fincrease[],float fcost[],float fgrossmin[],float fgrossmax[],float fnetmin[],float fnetmax[],float fnetave[])
{
for (int i=0;i<4;i++)
{
int acres=1000;
fcost[i]=acres*fcpa[i];
fgrossmin[i]=acres*fyield[i]*fper[i];
fgrossmax[i]=fgrossmin[i]+(fgrossmin[i]*fincrease[i]/100);
fnetmin[i]=fgrossmin[i]-fcost[i];
fnetmax[i]=fgrossmax[i]-fcost[i];
fnetave[i]=(fnetmin[i]+fnetmax[i])/2;
}
}
void getPrint(float fnetmin[],float fnetmax[],float fnetave[])
{
for (int i=0;i<4;i++)
{
cout<<"The minumum profit is:$ "<<fnetmin[i]<<endl;
cout<<"The maximum profit is:$ "<<fnetmax[i]<<endl;
cout<<"The average profit is:$ "<<fnetave[i]<<endl;
}
}
In the prototype you have written at the start of the program, this is written.
void getData(string,float,float,float,float) ;
It should be this instead identical to the one in its definition.
void getData(string,float[],float[],float[],float[]);
The function prototype should be same in its declaration and implementation.