Functions and structures in C++ - c++

/*I got stumped within my code. I think classes will be simpler than structures, but the chapter within my book makes me do structures. : / I am currently getting an error message that my function was not matched up for an overloaded function. The book does talk about them, but the examples of overloading functions in the book aren't helping me out. Also the book wants me to enter account numbers and fill in the objects and when they are asked for an account number they should have the opportunity to "QUIT" entering numbers and proceed onto the next part of the program; that whole way of thinking has my brain a bit fried and I was hoping I could get some help. I apologize if the formatting of my code is messy, I tried to reformat it within here so it would all go into the code brackets.
The Error happens at line... 161 at the displayAccounts function. Parameters were different within the top and bottom of the two functions I changed it and it works. I am going to go over different parts and if its correct post the correct code.*/
I figured out exactly the question that I need. I need the "QUIT" loop to be allowed to be followed up within the account numbers. This would allow the user to enter in a 0 at any time when asked to enter an account number and this was what was confusing me the most.
#include <iostream>
#include <iomanip>
using namespace std;
struct BankAccount
{
void enterAccountsData(BankAccount *accounts);
void computeInterest(BankAccount *accounts);
void displayAccounts(BankAccount *accounts, const int QUIT);
int accountNum; // holds the account number.
double accountBal; // holds the account balance.
double annualInterest; // holds the interest rate.
int term; // holds the term for the accounts.
};
int main()
{
const int MAX_ACCOUNTS = 100; // The maximum number of bank accounts.
const int QUIT = 0; // sentinal value.
int input;
int num = 0;
BankAccount data[MAX_ACCOUNTS];
BankAccount display;
cout << "Enter " << QUIT << " to stop, otherwise enter 1 and procreed.";
cin >> input;
while(true)
{
if(input != QUIT)
{
data[MAX_ACCOUNTS].enterAccountsData(data);
data[MAX_ACCOUNTS].computeInterest(data);
}
else
{
break;
}
}
display.displayAccounts(data, QUIT);
//system("pause");
return 0;
}
void BankAccount::enterAccountsData(BankAccount *accounts)
{
cout << setprecision(2) << fixed;
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts. (change the number for more bank accounts)
int found;
int quit = 0;
/* First for loop which asks and holds the account information
entered in by the user. */
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
do
{
found = 0;
cout << "Enter in account # " << (num + 1) << endl;
cin >> accounts[num].accountNum; // holds the value of the account number
// Checks if the account number is valid.
while(accounts[num].accountNum < 999 || accounts[num].accountNum > 10000)
{
cout << "Account number must be four didgets:" << endl;
cin >> accounts[num].accountNum;
}
// Checks if the account numbers are the same.
for(int check = 0; check < num; check++)
{
while(accounts[num].accountNum == accounts[check].accountNum)
{
cout << endl << "Account Numbers cannot be the same, enter in a new account number." << endl;
found = 1;
break;
}
}
} while(found); // end of do while.
// Holds the values for the account balances.
cout << "Enter the accounts balance." << endl;
cin >> accounts[num].accountBal;
// Makes sure that the account balance is not negative.
while(accounts[num].accountBal < 0)
{
cout << "Account cannot have a negitive balance." << endl;
cin >> accounts[num].accountBal;
}
// Holds the interest rate.
cout << endl << "Enter the interest rate for account # " << (num + 1) << endl;
cin >> accounts[num].annualInterest;
// Makes sure the interest rate is valid
while(accounts[num].annualInterest > 0 && accounts[num].annualInterest > 0.15)
{
cout << endl << "Annual interest must be from 0 to 0.15." << endl;
cin >> accounts[num].annualInterest;
}
// Makes sure the interest rate is not negetive
while(accounts[num].annualInterest < 0)
{
cout << endl << "Interest rate cannot be negetive" << endl;
cin >> accounts[num].annualInterest;
}
// Holds the value for the length of the interest.
cout << endl << "How many years will this interest rate be held for? " << endl;
cin >> accounts[num].term;
//Checks for valid length of time for the term held
while(accounts[num].term < 0 || accounts[num].term > 11)
{
cout << "The Term must be greater than 1 and should not exceed 10" << endl;
cin >> accounts[num].term;
}
}
cout << "If you wish to stop enter 0 otherwise type 1 to proceed" << endl;
cin >> quit;
if(quit = 0)
{
return;
}
}
void BankAccount :: computeInterest(BankAccount *accounts)
{
const int NUM_OF_ACCOUNTS = 100; // the number of bank accounts.
const int MONTHS_IN_YEAR = 12;
double total = 0;
double average = 0;
for(int num = 0; num < NUM_OF_ACCOUNTS; num++)
{
/*Goes through the term year and calculates the total
of each account balance. Then calculates the average. */
for(int year = 0; year < accounts[num].term; year++)
{
for(int month = 0; month < MONTHS_IN_YEAR; month++)
{
accounts[num].accountBal = (accounts[num].accountBal * accounts[num].annualInterest) + accounts[num].accountBal;
}
int month = 1;
cout << endl << "Total amount for account # " << (num + 1) << " is: " << accounts[num].accountBal << endl ;
total += accounts[num].accountBal;
cout << endl << "The total amount of all accounts is: " << total << endl;
}
}
average = total / NUM_OF_ACCOUNTS;
cout << "Average of all the bank accounts is: " << average << endl;
}
void BankAccount :: displayAccounts(BankAccount *accounts)
{
int input = 0;
int found;
const int MAX_ACCOUNTS = 100;
int quit = 0;
cout << endl << "Which account do you want to access?" << endl <<
"To stop or look at none of the account numbers type: " << quit << endl;
cin >> input;
for(int num = 0; num < MAX_ACCOUNTS; num++)
{
while(num < MAX_ACCOUNTS && input != accounts[num].accountNum)
{
num++;
}
if(input == accounts[num].accountNum) // This if sees if an account matches what the user entered.
{
cout << "Account: " << accounts[num].accountNum << endl << "Balance is: " <<
accounts[num].accountBal << endl << "Interest rate is: " << accounts[num].annualInterest;
cout << endl << "Enter another account number or type 0 to quit." << endl;
found = 1;
cout << endl;
cin >> input;
}
if(found == 0)
{
cout << "Sorry that account doesn't exist. Enter another account number." << endl;
cin >> input;
}
}
}

In C++, classes and structs are exactly the same constructs. They are, in fact, one thing — a User-Defined Type.
There is a different that is invoked depending on whether you used the keyword struct or class to define your UDT, and that is that class-key defaults to private member access and private inheritance, whereas struct-key defaults to both being public.
Other than this syntax difference, you can use either without worrying about one being "simpler" than the other.
Anyway, your compiler error (please provide it next time) is probably due to a declaration/definition mismatch.
Your declaration:
void displayAccounts(BankAccount *accounts, const int QUIT);
Start of your definition:
void BankAccount :: displayAccounts(BankAccount *accounts) {
The start of the definition should be
void BankAccount::displayAccounts(BankAccount* accounts, const int QUIT) {
to match. I've also fixed your spacing to be nicer. :)

void displayAccounts(BankAccount *accounts, const int QUIT);
... looks different between declaration and definition. Second parameter is missing in the definition.

Not sure what your question is, but classes and structs in C++ are equivalent except that fields are public by default in structs, but private by default in classes.

In the struct’s displayAccounts() member declaration you have:
void displayAccounts(BankAccount *accounts, const int QUIT);
and when defining the method later:
void BankAccount :: displayAccounts(BankAccount *accounts)
You have just missed
const int QUIT
parameter for the member function definition.

Related

How would I calcuate the total of all the items entered to then calculate the total price?

Hi there apologise if my question is poorly worded, I'm struggling to find a solution to my problem.
The purpose of my program is to allow the user to enter predefined bar codes that associate with items and a price. The user enters as many barcodes as they want, and when they're done they can exit the loop by pressing "F" and then total price for all the items is displayed.
This is my code so far, I'm very new to programming..
#include <iostream>
#include <iomanip>
using namespace std;
int index_of(int arr[], int item, int n) {
int i = 0;
while (i < n) {
if(arr[i] == item) {
return i;
}
i++;
}
return -1;
}
const int SIZE = 10;
int main()
{
string item [SIZE] = {"Milk", "Bread", "Chocolate", "Towel", "Toothpaste", "Soap", "Pen", "Biscuits", "Lamp", "Battery"};
int barcode [SIZE] = {120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009, 120010};
float price [SIZE] = {10.50, 5.50, 8.00, 12.10, 6.75, 5.20, 2.00, 4.45, 20.50, 10.00};
cout << "*************************************************************" << endl;
cout << "WELCOME TO THE CHECKOUT SYSTEM" << endl;
cout << "Please scan a barcode or manually enter the barcode ID number" << endl;
cout << "*************************************************************\n" << endl;
int newBarcode;
while (true){
cout << "Please enter a barcode (Type 'F' to finish): ", cin >> newBarcode;
int index = index_of(barcode, newBarcode, (sizeof(barcode) / sizeof(barcode)[0]));
cout << "\n>> Name of item: " << item[index] << endl;
cout << ">> Price of item: \x9C" << setprecision (4)<< price[index] << endl;
cout << ">> " <<item[index] << " has been added to your basket. \n" << endl;
float total = 0 + price[index];
cout << ">> Your current basket total is: \x9C" << setprecision(4) << total << endl;
/*float total = 0;
float newtotal = 0;
price[index] = total;
total = newtotal;
cout << ">> " << "Basket total: " << newtotal << endl; */
}
return 0;
}
You will need to iterate over all items and add their value to a variable. You can do it the old way:
float sum = 0;
for(int i = 0; i < SIZE; i++) {
sum += price [i];
}
Or the C++11 way:
float sum = 0;
for(float p : price) {
sum += p;
}
However I must point out a few important issues with your code:
Your array has a fixed size but user can enter as many entries as he wants. To avoid this issue, use vector. It behaves like array but has dynamic size. Simply use push_back() to add a new element.
Don't use separate containers (arrays) for the same group of objects. It's a bad coding practice. You can define a structure for product which will contain name, barcode and price, then make one container for all of the products.
Edit
I'm sorry, I misunderstood your problem. There are many ways to solve this, the most elegant way is to create a map where key is the bar code and value is your product object or just a price.
map<int, float> priceMap;
priceMap.insert(pair<int, float>([your bar code here], [your price here]))
Afterwards just create a vector of bar codes, fill it with user data and iterate over it sum all prices:
float sum = 0;
for(int b : userBarcodes) {
sum += priceMap.at(b);
}
You are trying to read from cin into an int. As you decide to put a stopping condition on 'F' input you must read into a string. Then decide what to do with the value. You will need to check if the input is an int or not. You can do it as given here or here.
Or you may change the stopping condition to a less likely integer like -1. And make sure you always read an int into newBarcode.
There are various small errors which are hard to list out. I have changed them in the code below which is implementing point 2 (You have to add the stopping condition).
One of the error or wrong practice is to declare new variables inside a loop. In most cases you can declare the variables outside and change there values in the loop.
I replaced (sizeof(barcode) / sizeof(barcode)[0] with SIZE as the lists are predefined and unchanging. Anyways you should use (sizeof(barcode) / sizeof(barcode[0]) for length calculation.
#include <iostream>
#include <iomanip>
using namespace std;
int index_of(int arr[], int item, int n) {
int i = 0;
while (i < n) {
if(arr[i] == item) {
return i;
}
i++;
}
return -1;
}
const int SIZE = 10;
int main()
{
string item [SIZE] = {"Milk", "Bread", "Chocolate", "Towel", "Toothpaste", "Soap", "Pen", "Biscuits", "Lamp", "Battery"};
int barcode [SIZE] = {120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009, 120010};
float price [SIZE] = {10.50, 5.50, 8.00, 12.10, 6.75, 5.20, 2.00, 4.45, 20.50, 10.00};
cout << "*************************************************************" << endl;
cout << "WELCOME TO THE CHECKOUT SYSTEM" << endl;
cout << "Please scan a barcode or manually enter the barcode ID number" << endl;
cout << "*************************************************************\n" << endl;
int newBarcode;
float total = 0;
int index;
while (true){
cout << "Please enter a barcode (Type -1 to finish): \n";
cin >> newBarcode;
while(cin.fail()) {
cout << "Not an integer" << endl;
cin.clear();
cin.ignore(100,'\n');
cin >> newBarcode;
}
index = index_of(barcode, newBarcode, SIZE);
cout << index;
if (index == -1) {
cout << "Apologies here for unsupported barcode\n";
continue;
} else {
cout << ">> Name of item: " << item[index] << endl;
cout << ">> Price of item: " << price[index] << "\n";
cout << ">> " <<item[index] << " has been added to your basket. \n";
total = total + price[index];
cout << ">> Your current basket total is: " << total << "\n";
}
}
return 0;
}
Your question could be more helpful to others if you find out what is wrong with your implementation and ask implementation specific questions which will probably be already answered. Asking what is wrong with my code is not quite specific.

I keep getting a variable uninitialized error when calling a function that is asking for user input

#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int numofEmployees();
int daysMissed(int);
int AverageMissed(int, int);
int main()
{
cout << "Welcome to employee absentee calculator!" << endl;
int numEmployees = numofEmployees();
int Missed = daysMissed(numEmployees);
double misAverage = AverageMissed(numEmployees, Missed);
cout << "There are " << numEmployees << " in the company. They have missed " << Missed << " days total. On average, they have missed " << misAverage << " days." << endl;
return 0;
}
int numofEmployees() {
cout << "How many employees are in your company? ";
int employees;
cin >> employees;
while (employees < 1) {
cout << "Employee count must 1 or greater!" << endl;
}
return employees;
}
int daysMissed(int numEmployees) {
int Absence, totAbsence = 0;
for (int i = numEmployees; i < numEmployees; i++) {
cout << "How many days has each employee missed this passed year? ";
cin >> Absence;
totAbsence += Absence;
}
while (Absence < 0) {
cout << "Values entered must be positive numbers!" << endl;
cin >> Absence;
}
return totAbsence;
}
int AverageMissed(int numEmployees, int Missed){
double Average;
Average = double(numEmployees) / double(Missed);
return Average;
}
This code is being used to calculate the average number of employee absences by way of using three functions. The second function is not working correctly as it is not being called properly by the main. This is for a school assignment.
The problem is daysMissed - if numEmployees is <= 0, then Absense will be uninitialized. But, you say, "I check that in numofEmployees" - the problem is that the compiler doesn't do that sort of whole-program analysis before issuing these warnings.
There is another problem: daysMissed is wrong (twice). If there are two employees, and I enter -2 and 1, there will be no error for the negative number. If on the other hand, if I enter 1 and -2, you never correct totAbsence. You would be much better off writing a little function which reads a number >= some limit in a loop, and keeps prompting until given the correct value. Something like:
int read(const char* prompt, const char* err_prompt, int limit) {
cout << prompt << endl;
for(;;) {
int result;
cin >> result;
if (result >= limit) {
return result;
}
cout << err_prompt << endl;
}
}
Then daysMissed becomes much pleasanter to write - and you can use the same function to read the number of employees (which will go into an infinite loop at the moment)
You should also validate a division by zero plus change the return type.
double AverageMissed(int numEmployees, int Missed){
if (Missed > 0) return double(numEmployees) / Missed;
return 0;
}
by the way, there is no need to cast both operands in the division (/). Casting one of them will be enough to return a double type.

Nested loops in C++ and user input

Pretty new here to programming, and I have an assignment where I need to achieve the following:
ask for total amount of people
get each of their names
allow user to enter up to 5 scores for each person
if there are less than 5 scores for a given person, inputting -100 will stop it
So far I have written this:
#include <iostream>
using namespace std;
int main() {
string personName;
int totalPerson, personScoreCounter;
double personGrade, personGradeTotal;
cout << "Input total amount of people: ";
cin >> totalPerson;
for (int person = 1; person <= totalPerson; person++)
{
cout << "Input name for person " << person << ": ";
getline(cin, personName);
cin.ignore();
while ( (personGrade != -100) && (personScoreCounter <= 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
if (personGrade >= 0 && personGrade <= 100) // valid range of scores
{
personGradeTotal += personGrade;
personScoreCounter++;
}
else
{
cout << "Input only scores from 0-100" << endl;
}
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
}
}
// calculate averages and other stuff in here.
return 0;
}
After getting their name, only the last cout inside the while loop seems to execute first, then it starts from the top and so on until the for loop hits the end depending on totalPerson. I know I'm missing a few things in here, probably in the order of operations and also the way I am executing my loops, but I just can't see it. Could any of you guys with experience in the language please give me any pointers as to what's happening here and how I can fix it? Thank you.
Inside your while group, you only want to use your cout line once (at the beginning looks good).
Your first check should be for ==-100 or similar, since as it is now, you'll get a "Input only scores from 0 to 100" message if you enter -100.
You should keep a cin.ignore(); call after each use of cin >> VARIABLE, since then you will drop the EoL character.
Example code:
#include <iostream>
using namespace std;
int main() {
int totalPerson;
cout << "Input total number of people: ";
cin >> totalPerson;
cin.ignore();
for (int person = 1; person <= totalPerson; person++)
{
int personScoreCounter=0;
double personGrade = -1, personGradeTotal=0;
string personName;
cout << "Input name for person " << person << ": ";
std::getline(cin, personName);
while ( (personGrade != -100) && (personScoreCounter < 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
cin.ignore();
if (personGrade == -100) {
break;
} else if (personGrade >= 0 && personGrade <= 100) {
personGradeTotal += personGrade;
personScoreCounter++;
} else {
cout << "Input only scores from 0-100" << endl;
}
}
// calculate averages and other stuff in here.
double avg = personGradeTotal / personScoreCounter;
cout << "Avg = " << avg << endl;
}
return 0;
}
Some of your variables also needed to move inside the for loop.
Additionally I changed the limits on the personScoreCounter to [0:4] rather than [1:5] - this way you can use it for averaging more easily.
You might also try cin.getline() instead of getline(std::cin , ... ):
int max_length = 30;
std::cin.getline(personName, max_length, '\n'); // \n is option termination.
This allows whitespaces in the input also.
http://www.cplusplus.com/reference/istream/istream/getline/

C++ Array parameters and const value

I do not get arrays, Im sure there are easier ways to make this program but I must do it the teacher's way and I am lost.
This is the assigment:
I do not get how I should go about these arrays. most confusing thing I seen by far.
What I would like is a guide or help on how i should program these arrays or how I should program arrays period. Not asking to do the rest for me, I already know how to do most of this, its just the arrays I like to know how to do.
This is my current program:
#include<iostream>
using namespace std;
void getPoints(int pPossible[], double pEarned[], int numItems, int limit);
int sumArray(double
void getpoints(int pPossible[], double pEarned[], int numItems, int limit)
{
int count;
while (limit == limit)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numbItems > limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
count=1;
for(count=1; count<numItems; count++)
cout << "Enter points then points possible for Item " << count << ": ";
cin << pEarned[count] << pPossible[count];
return 0;
}
C++ array indexes are zero-based, so you should use zero for the initial value in the for loop. Also, you're missing the braces for the for loop body; as it is, it will run the cout line numItem-1 times and the cin line just once.
Another thing: the operators in the for's cin line should be >>, not <<. You want input here, not output.
Finally, like #ebyrob said, make numItems a reference parameter (it would be clearer for the caller to use a pointer instead, but the assignment asked for a reference parameter).
void getpoints(int pPossible[], double pEarned[], int& numItems, int limit)
{
//Read number of items
while (true)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numItems >= limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
//Read earned and possible for each item
for(int count=0; count<numItems; count++)
{
cout << "Enter points then points possible for Item " << count << ": ";
cin >> pEarned[count] >> pPossible[count];
}
return 0;
}

C++ Class Variable Scope

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)