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 am working on a project and am stuck with what I think is a scope and a logic problem. I am creating a class called 'Person' with four string variables, last name, first name, favorite color, and gender. I am creating a second class called 'PersonList' with one variable that is an array of 'Person' objects. I have set a const int called MAX that determines the size of the array (currently 3). Ultimately, I would like to enter a the string variables of a 'Person' object into the 'newDude' object declared in the main. For instance, when the 'readNewPerson' function runs, I enter Doe, John, Blue, Male. THIS STEP WORKS!!
Next, I would like this 'newDude' to be copied into the 'dudesList' object declared in the main at address dudesList[0] and the 'readNewPerson' function to run again. If everything works correctly, I am thinking that Smith, Jane, Pink, Female should get copied to dudesList[1] and Johnson, Mike, Green, Male should get copied to dudesList[2]. Finally, I would like to print all three objects to the console.
I am going wrong somewhere in the 'for' loops within the 'addPersonToList' and 'printList' functions where my variable is not iterating properly. My guess is that since I am declaring the counter 'i' inside the function, it dies and resets to zero every time a 'newDude' is created. If I'm correct about this, where is the best place to declare the counter and when should I iterate it?
I really appreciate any feedback anyone might be able to offer and I certainly do not want anyone to DO the assignment for me. I could just use a bit of a push in the right direction at this point as I am incredibly frustrated with what should be a very simple task, at least in concept.
Here is my program so far:
// contact list with one-word strings only
#include <iostream>
using namespace std;
const int MAX = 3;
class Person
{
private:
string dudesLName;
string dudesFName;
string dudesColor;
string dudesGender;
public:
void readNewPerson (); // function declaration to ask for info
void printPerson (); //function declaration to display info to console
};
class PersonList
{
private:
Person dudesList [MAX];
public:
void addPersonToList (Person newDude); //function declaration to add my newDude to the dudesList array
void printList (); //function declaration to print the entire array
};
//the main function is a simple switch-case asking for user choices
int main (void)
{
Person newDude; //one object contains 4 simple string variables
PersonList List; //one object contains an array of [MAX] dudes
int userChoice; //integer for the user's choice in switch-case
cout << "~~Welcome to Stephen's Contact List~~" << endl;
cout << "Please enter your choice:" << endl;
cout << " 1 - enter " << MAX << " new people" << endl;
cout << " 2 - print the contact list" << endl;
cout << " 3 - retrieve by last name" << endl;
cout << " 4 - retrieve by address" << endl;
cout << " 5 - retrieve by gender" << endl;
cin >> userChoice;
switch (userChoice)
{
case 1:
for (int i = 0; i < MAX; i++)
{
newDude.readNewPerson (); //function call to enter one person's info
List.addPersonToList (newDude); //function call to add newDude to dudesList array
}
break;
case 2:
cout << "2 doesn't work yet" << endl;
List.printList (); //function call to print entire list
break;
case 3:
cout << "3 doesn't work yet" << endl;
break;
case 4:
cout << "4 doesn't work yet" << endl;
break;
case 5:
cout << "5 doesn't work yet" << endl;
break;
}
cout << "thanks dude!!" << endl;
return 0;
}
// function definitions
void Person::readNewPerson ()
{
cout << "enter a dude's last name please" << endl;
cin >> dudesLName;
cout << "enter a dude's first name please" << endl;
cin >> dudesFName;
cout << "enter a dude's favorite color please" << endl;
cout << "for test purposes, just enter one word" << endl;
cin >> dudesColor;
cout << "enter a dude's gender please" << endl;
cout << "male or female is fine, so is dude or dudette" << endl;
cin >> dudesGender;
return;
}
void Person::printPerson ()
{
cout << "dude's name is " << dudesLName << ", " << dudesFName << endl;
cout << "his (her?) favorite color is: " << endl;
cout << dudesColor << endl;
cout << "and his (her?) gender is: " << endl;
cout << dudesGender << endl << endl;
return;
}
void PersonList::addPersonToList (Person newDude)
{
for (int i = 0; i < MAX; i++) //supposed to iterate the array address as it adds Person objects to the array
dudesList [i] = newDude; //this is where the newDude object is copied to the array
return;
}
void PersonList::printList()
{
for (int i = 0; i < MAX; i++)
dudesList [i].printPerson ();
return;
}
Okay, what seems to be going wrong, is that you're adding the same person to the list 3 times. when you call addPersonToList
void PersonList::addPersonToList (Person newDude)
{
for (int i = 0; i < MAX; i++) //supposed to iterate the array address as it adds Person objects to the array
dudesList [i] = newDude; //this is where the newDude object is copied to the array
return;
}
now you have a couple of options.
What is probably the easiest to do and to concieve, is to pass the index into your method from where you call it, and make your method like this:
void PersonList::addPersonToList (Person newDude, int index)
{
dudesList [index] = newDude; //this is where the newDude object is copied to the array
}
and then in your switch statement, call it like this
case 1:
for (int i = 0; i < MAX; i++)
{
newDude.readNewPerson (); //function call to enter one person's info
List.addPersonToList (newDude, i); //function call to add newDude to dudesList array
}
Now what is probably the "right" way, is to keep track of what the last index you added was in your PersonList class
class PersonList
{
private:
Person dudesList [MAX];
int indexToAdd = 0; // your new index
public:
void addPersonToList (Person newDude); //function declaration to add my newDude to the dudesList array
void printList (); //function declaration to print the entire array
};
and then incriment that in your addPersonToList method
void PersonList::addPersonToList (Person newDude)
{
for (int i = 0; i < MAX; i++) //supposed to iterate the array address as it adds Person objects to the array
dudesList [indexToAdd] = newDude; //this is where the newDude object is copied to the array
indexToAdd++;
return;
}
Related
im trying to use parallel arrays and function to get user input for this menu/list im working on. the program should accept the name, surname and hours worked in the same function.
the error im facing is down below. please help me fix it
"main.cpp:38:28: error: cannot convert ‘std::string’ {aka ‘std::__cxx11::basic_string’} to ‘std::string*’ {aka ‘std::__cxx11::basic_string*’}
"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//globl const for array size
const int SIZE = 10;
// functions
void menuDisplay();
void getEmpDetails(string[], string[], int[]);
int main()
{
// declaring parrell arrays
string name[SIZE]; //for storing Employee names
string surname[SIZE]; // for storing Employee surname
int hoursWorked[SIZE]; // for storing employee hours worked
//calling the functions
menuDisplay();
getEmpDetails(name[SIZE], surname[SIZE], hoursWorked[SIZE]);
return 0;
}
void menuDisplay() {
char choice;
do { //this makes the menu repeat itself
cout << "[C]apture Employee details" << endl;
cout << "[L]ist Employee details" << endl;
cout << "[A]ll Employee Payslips" << endl;
cout << "[S]ingle Employee Payslips" << endl;
cout << "[E]xit" << endl;
cin >> choice;
switch (choice) {
case 0:
cout << "capture employee detail" << endl;
break;
case 1:
cout << "list employee details" << endl;
break;
case 2:
cout << "All Employee Payslips" << endl;
break;
case 3:
cout << "Single employee payslips" << endl;
break;
case 4:
cout << "Exit" << endl;
}
} while (choice == 'C' || choice == 'L' || choice == 'S' || choice == 'E' || choice == 'A'); //for selecting the right options on the menu
cout << "invaild choice, please choice either C,L,A,S,E" << endl; // if the wrong option is selected this appears
}
void getEmpDetails(string name[SIZE], string surname[SIZE], int hoursWorked[SIZE]) {
//this function is for capturing employee details
for (int x = 0; x < SIZE; x++) {
cout << "enter employee name" << endl;
cin >> name[SIZE];
cout << "enter employee surname" << endl;
cin >> surname[SIZE];
cout << "enter number of hours worked" << endl;
cin >> hoursWorked[SIZE];
}
}
void getEmpDetails(string[],string[], int[]);
This function is declared as taking three pointers as parameters. In both C and C++ function parameters that get declares as arrays are actually pointers, this is really
void getEmpDetails(string *,string *, int *);
You attempt to call this function as follows:
getEmpDetails(name[SIZE],surname[SIZE],hoursWorked[SIZE]);
This name is in array. If X is in array, in C and C++ X[n] means the nth value in the array. So the above code attempts to pass a single value in the array to this function. The SIZEth value. Which, to add insult to injury, doesn't even exist so that's undefined behavior right out of the gate.
Now, if you go and reread the error message it makes perfect sense. The compiler is complaining that you're trying to pass a string, that single value in the array, to a function that expects a string * parameter. That's obviously wrong.
Your obvious intent here is to pass the arrays, or pointers to the arrays, to this function, and not a single value from each array. If so, this is, simply:
getEmpDetails(name, surname, hoursWorked);
This should answer the question of the compilation error. But that won't solve all of your problem. Looking at what's in this function:
for (int x =0; x < SIZE; x++){
cout << "enter employee name" <<endl;
cin >> name[SIZE];
If you followed my explanation above, the problem here should now be obvious, as well as what it's obvious solution. Hint: name[SIZE] does not exist. Attempting to set it to anything will result in a crash. Ask yourself what exactly you want to happen here.
I'm very new at C++ and I am having trouble with my phone book program.
The issue is when I go to add a contact, it saves the name and number in the arrays. If I choose switch case 2 after adding each contact, it'll list all the contacts and phone numbers normally. But if I select switch case 1 multiple times in a row and add more than one contact before I select switch case 2 to display all the contacts, it will only print the most recent contact I added.
The code is unfinished, but I can't seem to figure this one out! When I add more than one contact at a time, does it override the most recent one I just added? Sorry if I am not explaining this well, I'm not yet familiar with all the proper terminology!
I also don't want to use a loop for the input, so the user will not have to input ten names and numbers all at once if they don't want to. Unless there's a way to use a loop and have them end it after a certain amount of entries.
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
using namespace std;
string nameArray[10];
string numberArray[10];
int arraySize = 10;
int index;
int i;
void addContact() {
// Get user input
cout << "\n\tEnter contact information" << endl;
cout << "\t==========================" << endl;
cout << "\tEnter name: ";
getline(cin, nameArray[i]);
cout << "\tEnter phone number: ";
cin >> numberArray[i];
cin.ignore();
}
void viewAll() {
// Declare variables
int pass = -1;
string tempNumber = "";
string tempName = "";
// Sort array in ascending order
for(pass=0; pass<9; pass++) {
for(index = 0; index < (9 - pass); index++) {
if(nameArray[index] > nameArray[index + 1]) {
tempName = nameArray[index];
nameArray[index] = nameArray[index + 1];
nameArray[index + 1] = tempName;
tempNumber = numberArray[index];
numberArray[index] = numberArray[index + 1];
numberArray[index + 1] = tempNumber;
}
}
}
// Print contacts after sort
cout << endl;
for(int j=0; j<arraySize; j++) {
cout << '\t' << nameArray[j] << '\t' << '\t' << numberArray[j] << endl;
}
}
void searchContact() {
}
void editContact() {
}
void deleteContact() {
}
int main() {
int choice;
while(1) {
cout << "\n\t\tMAIN MENU" << endl;
cout << "\t=======================" << endl;
cout << "\t [1] Add Contact" << endl;
cout << "\t [2] View All Contacts" << endl;
cout << "\t [3] Search Contact" << endl;
cout << "\t [4] Edit Contact" << endl;
cout << "\t [5] Delete Contact" << endl;
cout << "\t [6] Exit Program" << endl;
cout << "\t=======================" << endl;
cout << '\t';
cin >> choice;
switch(choice) {
case 1: // Add a new contact
cin.ignore();
addContact();
break;
case 2: // Print all contacts in alphabetical order
viewAll();
break;
case 3: // Search and print contact name and phone number
searchContact();
break;
case 4: // Edit a contact
editContact();
break;
case 5: // Delete a contact
deleteContact();
break;
case 6: // End program
return 0;
break;
default:
cout << "\nInvalid choice." << endl;
break;
}
}
return 0;
}
i think Johnny Mopp has given you the correct answer, but you said your new so i'd like to give you a slightly longer explanation, and a little bonus advice.
Consider your addContact function. You ask for values to be inserted into the name and numbers array at position i. You need to update that position after you add a contact or it will simply overwrite what was there previously. So a ++i; at the end of the function will solve your problem as this means next time you add a contact it goes to the next slot in the array. Now be mindful of this as your array only has (right now) 10 items in it, so once you add 10 entries i will have a value of 10 now which if you try to do nameArray[i] it would be trying to access, or worse write to, the 11th item in your array which does not exist, this is very bad (take a quick google tour of "buffer overflow error"). So make sure you add a safety check in at the start of addContact that checks if i == 10 in which case you could for example: print an error message then return from the function immediately. Definately DO NOT try to access an element of the array that does not exist.
I would also recommend explicitly initialising i to 0 just for clarity (it will be 0 because it is a global variable, but it would not be 0 if it was declared inside a function, so its a good habit to get into)
Finally, you seem to be using a mix of declaring a loop variable outside of the loop for(pass=0;...) and declaring it inside the loop for(int y = 0;...) from what i can see you dont use the variables declared outside of the loop like pass or index for anything except looping, so consider declaring them in the loop where they are used, this just keeps things a bit tidier and avoids mistakes where because the variable is still in scope someone might think its valid to use it as an array index or the likes.
Hope thats useful.
I must create a C++ program that asks the user to input different products information. So I created a structure to organize the members for the products, and I must use 3 functions, 1 to ask the user for their input, 1 to display the input, and 1 to display the last member Count for every Product item.
My code:
#include <iostream>
#include <string>
#include<fstream>
using namespace std;
struct Product //Structure
{
char Name[25]; //Product Name
char Type[25]; //Product Type
char Exp_Date[25]; //Product Expiration Date
double Price; //Product Price
double Discount_Percentage; //Product Discount Percentage
int Count; //Product Count in stock.
};
//Function Prototypes
Product Receive_Product_Information(Product);
void Display_All_Product_Information(Product & item);
void Display_Each_Product_Count(Product & item);
int main()
{
Product Item[2];
for (int i = 0; i < 2; i++)
{
cout << "Enter the product information for the number " << i+1 << "item" << endl;
Product item[2];
Item[i] = Receive_Product_Information(item[2]);
}
cout << "marker" << endl << endl;
for (int i = 0; i < 2; i++)
{
Product item[2];
Display_All_Product_Information(item[i]);
}
for (int i = 0; i < 2; i++)
{
Product item[2];
Display_Each_Product_Count(item[i]);
}
return 0;
}
//Function Definitions
Product Receive_Product_Information(Product item)
{
cout << "Enter Product Name: ";
cin>>item.Name;
cout << "Enter the Product Type: ";
cin>>item.Type;
cout << "Enter the Product Expiration Date: ";
cin>>item.Exp_Date;
cout << "Enter the Product Price: ";
cin >> item.Price;
cout << "Enter the Product Discount Price: ";
cin >> item.Discount_Percentage;
cout << "Enter the Product Count: ";
cin >> item.Count;
cout << endl << endl;
return item;
}
void Display_All_Product_Information(Product &item)
{
cout << "Name: " << item.Name<< endl;
cout << "Type: " << item.Type << endl;
cout << "Exp Date: " << item.Exp_Date << endl;
cout << "Price: $" << item.Price << endl;
cout << "Discount Percentage: " << item.Discount_Percentage << endl;
cout << "Count: " << item.Count << endl;
return ;
}
void Display_Each_Product_Count(Product &item)
{
cout << "Product Count: " << item.Count << endl;
return ;
}
My Problem:
My problem now is that the members Name, Type and Exp_Date are not being displayed as strings (i.e, Apple, Fruit, December) instead I get (##$%%#$%$%#)
I see multiple issues with this code:
for (int i = 1; i <= 2; i++)
This for statement executes a loop, with i set to 1, and 2, on its two iterations, respectively. Let's keep this in mind, while the rest of the loop is examined.
Product item[2];
This declares an array of two Products: item[0] and item[1]
Item[i] = Receive_Product_Information(item[i]);
The first bug here is on the second iteration, this will reference item[2], since i will be 2, see above.
Unfortunately, only item[0] and item[1] exist, this is undefined behavior. item is a two-element array, and in two element array you have element #0 and element #1. Not element #1 and element #2.
This also applies to the Item array too. It's actually worse in Item's case, since it's assigned to. The typical results on most implementations is a corrupted stack, and and a crash.
Product Receive_Product_Information(Product item)
The Receive_Product_information() function receives its argument by value. However, the argument was copied from an as-yet uninitialized locally-scoped object, in the caller's scope. Technically, this is not a 100% bug, but this is considered poor practice. Either the parameter should be passed by reference, or the object's contents should be properly initialized.
Additionally, it seems that passing the Product parameter does not really do anything usefl.Receive_Product_Information() appears to use standard input to initialize the contents of item ... and then immediately return it. So, why did it need it in the first place?
Receive_Product_Information() does not need this parameter at all. It simply needs to construct a new instance of Product by itself, and then return it.
There may or may not be other problems with this code, this is just what I immediately noticed, at first glance.
This is a board game created using C++. In order to win, one player must be able to reach the end of the board three times. But the problem is that it is the the first player who is entered into the board game that is always winning. I have a function setup so the that the simulated dice uses a random number-generator. How can I fix this issue?
#include <iostream>
using namespace std;
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <string>
#define SIZE 20 //EDITED: SIZE is Defined at 20 for the number of squares wanted for the board game. Makes is easier for change
//NOTE TO SELF: This is the revamped version. "EDITED" marks addition/change from 'assignment2_fixed.cpp
/**********************
* FUNCTION PROTOTYPES *
***********************/
void displayRules();
void action();
void firstRoll();
void showState();
int spinDie();
bool play();
bool winner();
int square[SIZE]; //For each square on the board, SIZE is Defined
const int loseTurn=1, switchPlace=2, goAgain=3, moveBack=4; //CONSTANT! Labels each action location for each square
int *location, *lastsq, *losTurn; //EDITED: Declared for dynamic allocation for location on board, last square of board, and lost turn
string *names; //EDITED: This is to hold the names of the players
int numPlayers = 0; //Holds the number of players
int turn; //EDITED: First players turn
/************
* FUNCTIONS *
*************/
void displayRules(){ //Displays the rules to the player once the game starts
cout << "Welcome to 3X" << endl;
cout << "The first player to go around the board three times wins!" <<endl;
cout << "The player with the lowest number goes first" << endl;
cout << "The players take turns until one player wins" << endl;
cout << "The players must move forward the number of spaces the die displays" << endl;
cout << "If the player lands on a square with an action, the player must perform that action, otherwise the next player goes" <<endl;
cout << endl << endl;
}
void action(){ //EDITED: This lists actions for each square
square[2] = goAgain;
square[4] = switchPlace;
square[6] = goAgain;
square[8] = loseTurn;
square[11] = goAgain;
square[14] = moveBack;
square[16] = switchPlace;
square[18] = loseTurn;
}
void firstRoll(){ //EDITED: Initializes for the first die roll
numPlayers = spinDie();
for(int i=0; i<numPlayers; i++)
location[i];
for(int i=0; i<numPlayers; i++)
lastsq[i];
for(int i=0; i<numPlayers; i++)
losTurn[i];
}
void showState(){
for(int i=0; i<numPlayers; i++){
cout << "Player " << names[i] << " is at location " << location[i] << endl;
}
for(int i=0; i<numPlayers; i++){
cout << names[i] << " lands on last space " << lastsq[i] << " times " << endl;
}
}
int spinDie(){ //For the dice. Number is generated randomly based on time
int x = rand()%6 +1 ;
cout<< " a "<< x<< " was rolled"<<endl;
return x;
}
bool play(){ //EDITED: Play function through squares
srand(time(0));
while(true){
if(losTurn[turn]){
losTurn[turn] = 0;//EDITED: Finds if player lost turn based on the value of 'turn'
turn = (turn) % numPlayers;
continue;
}
cout << "Turn: "<< names[turn] << endl;
int spot = spinDie(); //EDITED: Players spot on the board based on random number generator
cout << "Number on die : " << spot << endl;
location[turn] += spot;
if(location[turn] >= SIZE-1){
location[turn] -= SIZE;
lastsq[turn]++;
cout << names[turn] << " passes End!"<<endl;
if(winner())
return true;
}
switch(square[location[turn]]){
case goAgain:
cout<<"Action: Go again.\n";
showState();
break;
case loseTurn:
cout<<"Action: Lose turn.\n";
losTurn[turn] += 1;
break;
case switchPlace:
cout<<"Action: Switch places\n";
break;
case moveBack:
cout<<"Action: Move back 2 places.\n";
location[turn] -= 2;
break;
default:
cout<<"Action: None\n";
}
showState();
turn = (turn) % numPlayers;
}
return false;
}
bool winner(){ //Finds the winner who hits the end square three times
if(lastsq[turn] == 3){
cout<<"\n"<<names[turn]<<" WIN!\n";//Prints name of player with their turn
return true;
}
return false;
}
/***************
* MAIN PROGRAM *
****************/
int main(){
srand(time(0)); //Makes time based number in die random
displayRules(); //Diplays the rules first
cout << "Please type in the number of players between 1-6 : " << endl;
cin >> numPlayers;
while ((numPlayers < 1) || (numPlayers > 6)) //EDITED: Guard against any values outside of 1-6
{
cout << "ERROR: Enter a value from 1 - 6: ";
cin >> numPlayers;
}
names = new string[numPlayers]; //EDITED: Dynamically allocates array of string to hold names of players
location = new int[numPlayers]; //EDITED: Dynamically allocates array of int to hold locations of players
losTurn = new int[numPlayers]; //EDITED: Dynamically allocates array of int to hold lost turn of players
lastsq = new int[numPlayers]; //EDITED: Dynamically allocates array of int to hold count of each time player reach end square
for(int i=0; i<numPlayers; i++){
cout << "Enter name of player " << i+1 << " " << endl; //EDITED: To get name of each player starting with Player 1 (i+1)
cin >> names[i]; //EDITED: Gets names of players into the dynamically allocated strings
}
while(true){//EDITED: Continues the loop
if(play())//EDITED: If the "Play" function is true
break;//EDITED: Breaks once the winner is found
}
return 0;
}
Although your question is vague, I can give you some help to start you off. First off I'm going to show your code for the random factor on the dice.
int spinDie(){ //For the dice. Number is generated randomly based on time
int x = rand()%6 +1 ;
cout<< " a "<< x<< " was rolled"<<endl;
return x;
This code makes it so that the compiler will generate ANY number within an integer range. Then you divide that random number by 6 and find the remainder with the remainder operator (%). The +1 will add to the remainder if it is a factor of 6 such as 36. Your code is fine. The problem is that it is based off of time. The first one on the board probably gets similar or the same numbers each time and the second one does too. Which would explain the first one always winning. I'm assuming the first one gets similar or the same rolls every time because of your lack of explanation of the SPECIFIC problem. Hope this helped a little lol.
I have a question about variable scope in a C++ class. The problem I'm working on says to create a class that holds an array of structures, with each structure holding the name, cost, and amount for a particular type of drink.
The class should have public member functions to buy a drink and display the menu, and private functions to get and validate money input (called by buy_drink) and to display an end of day report (called by the destructor).
I have a problem with the scope in the private function input_money. I get an error saying that the array has not been defined yet. I tested the display_data function (for printing the menu), and it worked fine on its own, but now I can't figure out why input_money would have a scope error and display_data wouldn't. Here is the header file:
/* need to create a class that holds an array of
5 structures, each structure holding string drink name,
double cost, and int number in machine
class needs public functions to display data and
buy drink
private functions input money -- called by buy_drink to accept,
validate, and return to buy drink the amount of money input
daily report -- destructor that reports how much money
was made daily and how many pops are left in machine */
#ifndef DRINKS_H
#define DRINKS_H
#include <string>
class Drinks
{
private:
struct Menu
{
std::string name;
double cost;
int number;
};
Menu list[5]; // array of 5 menu structures
double money_made; // track money made during the day
double input_money(int); // return validated money to buy_drink()
void daily_report(); // called by deconstructor
public:
Drinks();
~Drinks();
void display_data();
void buy_drink(int);
};
#endif
And here is the implementation file:
/* implementation file for Drinks class */
#include <iostream>
#include <string>
#include "drinks.h"
using namespace std;
const int SIZE = 5;
const int START_SIZE = 100;
Drinks::Drinks()
{
list[0].name = "Coke";
list[1].name = "Root Beer";
list[2].name = "Orange Soda";
list[3].name = "Grape Soda";
list[4].name = "Bottled Water";
for (int count = 0; count < (SIZE-1); count++)
list[count].cost = .75;
list[4].cost = 1;
for (int count = 0; count < SIZE; count++)
list[count].number = 20;
money_made = 0;
}
void Drinks::display_data()
{
for (int count = 0; count < SIZE; count++) {
if (count == 0)
cout << count+1 << list[count].name << "\t\t$ ";
else
cout << count+1 << list[count].name << "\t$ ";
cout << list[count].cost << "\t"
<< list[count].number << endl;
}
}
double input_money(int c)
{
double input;
cin >> input;
while (input != list[c].cost) {
if (input < list[c].cost) {
cout << "Not enough money.\n"
<< "Enter " << list[c].cost - input
<< " more cents to buy\n\n> ";
cin >> input;
}
else if (input > list[c].cost) {
cout << "Too much money.\n"
<< "I only need $" << list[c].cost << endl
<< "Enter " << input - list[c].cost
<< " less money: ";
cin >> input;
}
}
return input;
}
void Drinks::buy_drink(int c) // this receives an int choice (to access corresponding structure in the list array)
{
double input;
cout << "Enter " <<list[c].cost
<< " to purchase " << list[c].name
<< "\n\n> ";
input = input_money(c); // input money returns a validated and accurate price for the drink and is passed the choice to access array
list[c].number -= 1;
money_made += list[c].cost; // add cost of drink to money made
}
void Drinks::daily_report()
{
int end_size = 0;
for (int count = 0; count < SIZE; count++)
end_size += list[count].number;
cout << "Today, you made $" << money_made << endl;
cout << "There are " << START_SIZE - end_size
<< " drinks left in the machine" << endl;
}
Drinks::~Drinks()
{
daily_report();
cout << "goodbye mr anderson\n";
}
Any help would be much appreciated! I can't seem to figure out why the input_money function does not have access to the structures in the array.
Thank you!
EDIT: Total noob mistake/carelessness. Forgot to add the name of the class in the input_money function definition and use the scope resolution operator (i.e. should be Drinks::input_money(int c)). Thanks to those who answered.
double Drinks::input_money(int c)
// ^^^^^^^^ forgot this
You forgot the class name while providing the implementation.
Notice the difference between your definition of
void Drinks::display_data
and
double input_money(int c)
In the second case you have defined a free function that is not a member of the class and has no information about the class members. It should be
double Drinks::input_money(int c)