So, I just had a question about my professors feedback on one of the programs we did. I didn't quite understand her feedback on what she meant by putting setters functions in the second constructor. Here is what she said:
Next time be sure to do the Reading and Preparation assigned before you attempt a lab. Read the assignment carefully.
The problem says the overloaded constructor (constructor #2) should call the setter functions.
The overloaded constructor (constructor #2) was not tested. Create an object with the overloaded constructor like so: Inventory itemTwo(666,3,.99);
Nice class, nice main program and coding style.
This was the problem:
Problem
And lastly, here's my code:
#include <iostream>
#include <iomanip>
using namespace std;
class Inventory
{
private:
int itemNumber; //Private Class Members
int quanity;
double cost;
public:
Inventory(); //Public Member Functions
Inventory(int i, int q, double c);
void setItemNumber(int);
void setQuanity(int);
void setCost(double);
int getItemNumber() const;
int getQuanity() const;
double getCost() const;
double getTotalCost() const;
};
int main()
{
int itemNum;
int qty;
double price;
Inventory itemOne; //Declares itemOne and itemTwo being an Inventory class objects
Inventory itemTwo;
/****************************************************************************/
cout << "Please Enter Data For Item One\n"; //Data entry for Item One
cout << "Enter item number: ";
cin >> itemNum;
while (itemNum < 0) //Safegaurds for data
{
cout << "Please enter a non-negative item number: ";
cin >> itemNum;
}
cout << "Enter quanity: ";
cin >> qty;
while (qty < 0)
{
cout << "Please enter a non-negative quanity number: ";
cin >> qty;
}
cout << "Enter price: ";
cin >> price;
while (price < 0)
{
cout << "Please enter a non-negative price: ";
cin >> price;
}
itemOne.setItemNumber(itemNum); //Passes All Data To Correct Functions
itemOne.setQuanity(qty);
itemOne.setCost(price);
cout << endl; //Formatting
/****************************************************************************/
cout << "Please Enter Data For Item Two\n"; //Data Entry for Item Two
cout << "Enter item number: ";
cin >> itemNum;
while (itemNum < 0)
{
cout << "Please enter a non-negative item number: ";
cin >> itemNum;
}
cout << "Enter quanity: ";
cin >> qty;
while (qty < 0)
{
cout << "Please enter a non-negative quanity number: ";
cin >> qty;
}
cout << "Enter price: ";
cin >> price;
while (price < 0)
{
cout << "Please enter a non-negative price: ";
cin >> price;
}
itemTwo.setItemNumber(itemNum); //Passes All Data To Correct Functions
itemTwo.setQuanity(qty);
itemTwo.setCost(price);
cout << endl; //Formatting
/****************************************************************************/
cout << fixed << showpoint << setprecision(2);
//All input displayed here
cout << "Here's the data you entered for item one:\n";
cout << "Item Number: " << " " << itemOne.getItemNumber() << endl;
cout << "Item Quanity: " << " " << itemOne.getQuanity() << endl;
cout << "Item Cost: " << " " << "$" << itemOne.getCost() << endl;
cout << "Item Total Cost: " << " " <<"$" << itemOne.getTotalCost() << endl << endl;
cout << "Here's the data you entered for item two:\n";
cout << "Item Number: " << " " << itemTwo.getItemNumber() << endl;
cout << "Item Quanity: " << " " << itemTwo.getQuanity() << endl;
cout << "Item Cost: " << " " << "$" << itemTwo.getCost() << endl;
cout << "Item Total Cost: " << " " <<"$" << itemTwo.getTotalCost() << endl;
return 0;
}
Inventory::Inventory() //Default Constructor
{
itemNumber = 0;
quanity = 0;
cost = 0;
}
Inventory::Inventory(int i, int q, double c) //Constructor #2
{
itemNumber = i;
quanity = q;
cost = c;
}
void Inventory::setItemNumber(int i) //Re-Evaluates For a Negative Number and
{ //Passes User's Entered Data to the Private class
if (i >= 0)
itemNumber = i;
else
itemNumber = 0;
}
void Inventory::setQuanity(int q) //Re-Evaluates For a Negative Number and
{ //Passes User's Entered Data to the Private class
if (q >= 0)
quanity = q;
else
quanity = 0;
}
void Inventory::setCost(double c) ////Re-Evaluates For a Negative Number and
{ //Passes User's Entered Data to the Private class
if (c >= 0)
cost = c;
else
cost = 0;
}
int Inventory::getItemNumber() const //All 'Getter' Functions to Display Object's Data
{ //Whilst Keeping Data Integrity With 'const'
return itemNumber;
}
int Inventory::getQuanity() const
{
return quanity;
}
double Inventory::getCost() const
{
return cost;
}
double Inventory::getTotalCost() const //Calculates Total Cost and Returns
{
return cost * quanity;
}
/*
-----------------------------------------------------
Please Enter Data For Item One
Enter item number: 1303
Enter quanity: 10
Enter price: 2.50
Please Enter Data For Item Two
Enter item number: 5676
Enter quanity: 54
Enter price: 5.65
Here's the data you entered for item one:
Item Number: 1303
Item Quanity: 10
Item Cost: $2.50
Item Total Cost: $25.00
Here's the data you entered for item two:
Item Number: 5676
Item Quanity: 54
Item Cost: $5.65
Item Total Cost: $305.10
-----------------------------------------------------
Please Enter Data For Item One
Enter item number: 7456
Enter quanity: 10
Enter price: 10.9
Please Enter Data For Item Two
Enter item number: 0293
Enter quanity: 5
Enter price: 109.23
Here's the data you entered for item one:
Item Number: 7456
Item Quanity: 10
Item Cost: $10.90
Item Total Cost: $109.00
Here's the data you entered for item two:
Item Number: 293
Item Quanity: 5
Item Cost: $109.23
Item Total Cost: $546.15
-----------------------------------------------------
*/
Your professor probably meant that you should call the setter functions in the constructor instead of setting the values directly:
Inventory::Inventory(int i, int q, double c) //Constructor #2
{
setItemNumber(i);
setQuantity(q);
setCost(c);
}
She's right. You are taking user input, therefore you must validate it with your setters, you created them for a reason.
Inventory::Inventory(int i, int q, double c) //Constructor #2
{
setItemNumber(i);
setQuantity(q);
setCost(c);
}
Related
So I am trying to create a ATM system that lets user to input value such as Account number, account name and amount. But I can't figure out what exactly I have to do
int AccNum[2];
string AccName[2];
float AccBal[2];
cout << "********** ENTER ACCOUNT **********"<<endl;
for(int num = 0; num < 2; num++){
cout << "Enter Account number: ";
cin >> AccNum[num];
for(int name = num; name < 2; name++){
cout << "Enter Account Name: ";
getline(cin, AccName[name]);
for(int bal = name; bal < 2; bal++){
cout << "Enter Amount: ";
cin >> AccBal[bal];
}
}
}
I have tried something like this but it does not give the result that I want. The ideal result would be
********** ENTER ACCOUNT **********
Enter Account number: 1231232
Enter Account name: James white
Enter amount: 1000
it will run 2 times so there would be 2 accounts after this loop that will have a result like this
********** THE ACCOUNT IS **********
Account number: 1231232
Account name: James white
Balance: 1000
So the code you wrote is nearly good. Too many loops in my opinion
int AccNum[2];
string AccName[2];
float AccBal[2];
cout << "********** ENTER ACCOUNT **********"<<endl;
for(int num = 0; num < 2; num++){ // lets call this loop a. happens 2 times
cout << "Enter Account number: ";
cin >> AccNum[num];
for(int name = num; name < 2; name++){ // loop b happens 2 times * loop a times
cout << "Enter Account Name: ";
getline(cin, AccName[name]);
for(int bal = name; bal < 2; bal++){ loop c = 2 * a * b = 8
cout << "Enter Amount: ";
cin >> AccBal[bal];
}
}
}
Direct fix:
int main()
{
int AccNum[2];
string AccName[2];
float AccBal[2];
cout << "********** ENTER ACCOUNT **********" << endl;
for(int num = 0; num < 2; num++){
cout << "Enter Account number: ";
cin >> AccNum[num];
cout << "Enter Account Name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, AccName[num]);
cout << "Enter Amount: ";
cin >> AccBal[num];
}
for(int i = 0; i < 2; i++)
cout << "********** ENTER ACCOUNT **********" << endl
<< "Account number: " << AccNum[i] << endl
<< "Account name: " << AccName[i] << endl
<< "Balance: " << AccBal[i] << endl << endl;
}
But if you want to expand it a little bit:
#include <iostream>
#include <vector>
using namespace std;
struct Account
{
int Number;
string Name;
float Balance;
Account(int num, string nam, float bal) : Number(num), Name(nam), Balance(bal) {}
Account() {}
void getData()
{
cout << "Enter Account number: ";
cin >> Number;
cout << "Enter Account Name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, Name);
cout << "Enter Amount: ";
cin >> Balance;
}
void printAccount()
{
cout << "********** ENTER ACCOUNT **********" << endl
<< "Account number: " << Number << endl
<< "Account name: " << Name << endl
<< "Balance: " << Balance << endl << endl;
}
};
int main()
{
vector<Account> accounts;
for(int i = 0; i < 2; i++)
{
Account person;
person.getData();
accounts.emplace_back(person);
}
for(int i = 0; i < 2; i++) accounts[i].printAccount();
}
Both codes give the exact same output:
When I try to compile, I get only two error messages.
"Error LNK2019 unresolved external symbol "int __cdecl examAvg(void)" (?examAvg##YAHXZ) referenced in function _main
Line 1
and
LNK1120 1 unresolved externals
also on Line 1
I have worked on this so long (days) that I really can't figure out where I am going wrong anymore, I am sure it is something simple, but I am for a loss again.
Will someone please give me a suggestion to help rectify the error codes?
/*
Christopher Pierce
Date Created: July 3, 2020
Egrades Vector Application
*This application creates a C++ menu program that generates an electronic grade sheet that can keep track of five student test scores earned during the semester.
• Organizes the main program menu to call four functions.
• (1) function that allow a user to Add five students and their scores on three exams into the vector.
• (2) function that will compute the average test score for each of the five students in the vector.
• (3) function that all the user to display a student average test scores searching for their name in the vector.
• (4) function that will compute the average of the average exams in the vector and display the result.
*/
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
// Declarations
int score1;
int score2;
int score3;
int score4;
int score5;
int score6;
int score7;
int score8;
int score9;
int score10;
int score11;
int score12;
int score13;
int score14;
int score15;
string student1;
string student2;
string student3;
string student4;
string student5;
int main()
{
vector <string> StudentFile;
vector <int> Egrades;
int average1 = (score1 + score2 + score3) / 3;
int average2 = (score4 + score5 + score6) / 3;
int average3 = (score7 + score8 + score9) / 3;
int average4 = (score10 + score11 + score12) / 3;
int average5 = (score13 + score14 + score15) / 3;
// Prototype (functions)
int examAvg();
{
StudentFile.insert(StudentFile.begin(), student1);
Egrades.insert(Egrades.begin(), average1);
StudentFile.push_back(student2);
Egrades.push_back(average2);
StudentFile.push_back(student3);
Egrades.push_back(average3);
StudentFile.push_back(student4);
Egrades.push_back(average4);
StudentFile.push_back(student5);
Egrades.push_back(average5);
}
/*
Start of Menu
*/
// Defines the width of the menu
const int menuWidth = 84;
// This is a loop structure for the menu box using ASCII
// This prints the top left corner of the menu box (ASCII)
cout << char(201);
// This prints the top border of the menu box (ASCII)
for (int column = 0; column < menuWidth; ++column) {
cout << char(205);
}
// This prints the top right corner of the menu box (ASCII)
cout << char(187);
cout << "\n";
// array with menu options
string menu[15];
menu[0] = " **************";
menu[1] = " *** MAIN MENU ***";
menu[2] = " **************";
menu[3] = " Please Choose From The Following Options:";
menu[6] = " 1. Add 5 Students to Egrades Vector:";
menu[8] = " 2. Compute Student Test Score Average:";
menu[10] = " 3. Search A Student Average Test Score:";
menu[12] = " 4. Compute The Average Of All 5 Student Exam Averages:";
menu[14] = " 5. Exit";
for (string option : menu)
{
cout << char(186) // print left border
<< setw(menuWidth) // set next item width
<< left // set next item aligment
<< option // print menu option string with width and aligment
<< char(186) << "\n"; // print right border
}
// This will print the bottom left corner of the menu box (ASCII)
cout << char(200);
// This prints the bottom border of the menu box (ASCII)
for (int column = 0; column < menuWidth; ++column) {
cout << char(205);
}
// This prints the bottom right corner of the menu box (ASCII)
cout << char(188);
cout << "\n\n";
/*
END OF MENU
*/
char selection;
cout << "\t\t\t Enter Your Selection: ", cin >> selection, cout << endl;
switch (selection)
{
case '1':
system("CLS");
cout << "Student Information Section:\n\n";
// Student 1 Info, captures name and scores
cout << "\nEnter Student 1 Name: \n";
cin >> student1;
cout << "\nEnter Exam 1 Score: ";
cin >> score1;
cout << "Enter Exam 2 Score: ";
cin >> score2;
cout << "Enter Exam 3 Score: ";
cin >> score3; examAvg();
// Student 2 Info, captures name and scores
cout << "\nEnter Student 2 Name:\n";
cin >> student2;
cout << "\nEnter Exam 1 Score: ";
cin >> score4;
cout << "Enter Exam 2 Score: ";
cin >> score5;
cout << "Enter Exam 3 Score: ";
cin >> score6; examAvg();
// Student 3 Info, captures name and scores
cout << "\nEnter Student 3 Name:\n";
cin >> student3;
cout << "\nEnter Exam 1 Score: ";
cin >> score7;
cout << "Enter Exam 2 Score: ";
cin >> score8;
cout << "Enter Exam 3 Score: ";
cin >> score9; examAvg();
// Student 4 Info, captures name and scores
cout << "\nEnter Student 4 Name:\n";
cin >> student4;
cout << "\nEnter Exam 1 Score: ";
cin >> score10;
cout << "Enter Exam 2 Score: ";
cin >> score11;
cout << "Enter Exam 3 Score: ";
cin >> score12; examAvg();
// Student 5 Info, captures name and scores
cout << "\nEnter Student 5 Name:\n";
cin >> student5;
cout << "\nEnter Exam 1 Score: ";
cin >> score13;
cout << "Enter Exam 2 Score: ";
cin >> score14;
cout << "Enter Exam 3 Score: ";
cin >> score15; examAvg();
cout << "\n\n******************************************************\n";
cout << "!!! INFORMATION HAS BEEN ADDED TO EGRADES VECTOR !!!\n";
cout << "******************************************************\n\n";
cout << "To Return To Main Menu:\n\n";
system("pause");
return main();
break;
case '2':
system("CLS");
for (unsigned int i = 0; i < Egrades.size(); ++i)
{
cout << Egrades[i] << endl;
}
cout << "To Return To Main Menu:\n\n";
system("pause");
return main();
break;
case '3':
system("CLS");
int score;
cout << "\nEnter A Students Name To Find Their Average:\n";
cin >> score;
if (cin >> student1)
{
cout << "Average Found:\n" << average1;
}
else if (cin >> student2)
{
cout << "Average Found:\n" << average2;
}
else if (cin >> student3)
{
cout << "Average Found:\n" << average3;
}
else if (cin >> student4)
{
cout << "Average Found:\n" << average4;
}
else if (cin >> student5)
{
cout << "Average Found:\n" << average5;
}
else
{
cout << "Average not found.\n";
}
cout << "To Return To Main Menu:\n\n";
system("pause");
return main();
break;
case '4':
system("CLS");
cout << "The Average of All Five Students Averages Are:\n\n";
cout << "|| " << (average1 + average2 + average3 + average4 + average5) / 5 << " ||\n\n";
cout << "To Return To Main Menu:\n\n";
system("pause");
return main();
break;
case '5':
exit(-1);
break;
default: cout << "\n Invalid selection\n\n";
}
return 0;
}
I trying to write a program that asks the user for movie information. stores the information of a movie as a struct in a vector and then output the result to the screen with the 2 functions having a return type of void.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
using namespace std;
void make_movie(struct movie *film);
void show_movie(vector <movie> data, int cnt);
struct movie {
string name;
string director;
int year;
int duration;
};
int main() {
int count = 0;
char input;
vector <movie> record;
movie *entry = nullptr;
do {
make_movie(entry);
record.push_back(*entry);
count++;
cout << endl;
cout << "Do you have more movie info to enter?\n";
cout << "Enter y / Y for yes or n / N for no: ";
cin.ignore();
cin >> input;
cout << endl;
} while (input == 'y' || input == 'Y');
show_movie(record, record.size());
return 0;
}
void make_movie(struct movie *film) {
cout << "Enter the title of the movie: ";
cin.ignore();
getline(cin, film -> name);
cout << "Enter the director's name: ";
cin.ignore();
getline(cin, film -> director);
cout << "Enter the year the movie was created: ";
cin >> film -> year;
cout << "Enter the movie length (in minutes): ";
cin >> film -> duration;
}
void show_movie(vector <movie> data, int cnt) {
cout << "Here is the info that you entered: " << endl;
for (int i = 0; i < cnt; i++) {
cout << "Movie Title: " << data[i].name << endl;
cout << "Movie Director: " << data[i].director << endl;
cout << "Movie Year: " << data[i].year << endl;
cout << "Movie Length: " << data[i].duration << endl;
cout << endl;
}
}
I am getting a error that says that i am trying to access a prohibited memory address.
The least amount of changes you need to make is to change:
movie *entry = nullptr;
do {
make_movie(entry);
record.push_back(*entry);
to:
movie entry;
do {
make_movie(&entry);
record.push_back(entry);
Further improvements would be:
Change make_movie to accept parameter by reference, then your program does not use any pointers and therefore is not vulnerable to any of the problems associated with pointers.
Change make_movie to return by value instead of taking a reference parameter.
cin.ignore(); is being used incorrectly. Your program will lose the first character of several of the input strings. Instead, remove all of those calls, and at the end of the make_movie function, ignore the rest of the current line. Also, change cin >> input; to use getline.
your bug
movie *entry = nullptr;
and
you have extra cin.ignore();
cout << "Enter the title of the movie: ";
// cin.ignore();
getline(cin, film -> name);
cout << "Enter the director's name: ";
// cin.ignore();
getline(cin, film -> director);
how to fix
movie main_info;
movie* entry = &main_info;
test
intput:
Enter the title of the movie: any_thing
Enter the director's name: yourself
Enter the year the movie was created: 2016
Enter the movie length (in minutes): 120
Do you have more movie info to enter?
Enter y / Y for yes or n / N for no: n
output
Here is the info that you entered:
Movie Title: any_thing
Movie Director: yourself
Movie Year: 2016
Movie Length: 120
//Amanda Genise
//CSC123 - Part 3
//08/06/2015
#include <iostream>
#include <string>
using namespace std;
class gamelist
{
private:
int gamecount;
//gameobject gameobjs[10];
public:
void add_game();
void print_list();
float total_value();
};
class gameobject
{
public:
void set_id_num(int num);
int get_id_num();
void set_name(string name1);
string get_name();
void set_type(int type_of_game);
string get_type();
void set_buy_value(float buy_game);
float get_buy_value();
void set_market_value(float market_price);
float get_market_value();
void set_year(int year1);
int get_year();
private:
int id_num;//identifier number for the game
string name;//the name of the game
int type;//whether the game is cartridge, CD, DVD, BR, download
string type_name;//type of game
float buy_value;//price of game
float market_value;//value of game
int year;//year the game was made
};
int main()
{
int option;//menu choice
do
{
//menu
cout << endl;
cout << "Please choose an option from the below menu. " << endl;
cout << "1. Add Game" << endl;
cout << "2. Print List" << endl;
cout << "3. Total value of collection" << endl;
cout << "4. Delete Game" << endl;
cout << "5. Exit" << endl;
cout << "Which would you like to execute? ";
cin >> option;
cin.ignore();
//to add a game
if (option == 1)
{
gamelist run;
run.add_game();
}
else if (option == 2)
{
gamelist run;
run.print_list();
}
} while (option != 5);
if (option == 5)
return 0;
}
void gamelist::add_game()
{
gameobject test;
int id;
string name_game;
int type_game;
int buy;
int market;
int year_game;
cout << "Please enter an id number for the game: ";
cin >> id;
test.set_id_num(id);//passes value
cout << "Please enter a name for the game: ";
cin.ignore();
getline(cin, name_game);
test.set_name(name_game);//passes value
cin.ignore();
cout << "There are four types of games." << endl;
cout << " 0. Cartridge " << endl;
cout << " 1. CD " << endl;
cout << " 2. DVD " << endl;
cout << " 3. BR " << endl;
cout << " 4. Download " << endl;
cout << "Which type do you want to set for the game (enter number)? ";
cin >> type_game;
test.set_type(type_game);//passes value
cout << "Please set a buying value for the game: ";
cin >> buy;
test.set_buy_value(buy);//passes value
cout << "Please set the market value of the game: ";
cin >> market;
test.set_market_value(market);//passes value
cout << "What is the model year of the game? ";
cin >> year_game;
test.set_year(year_game);//passes value
}
//sets id num for the game
void gameobject::set_id_num(int num)
{
id_num = num;
}
//displays the id num for the game
int gameobject::get_id_num()
{
return(id_num);
}
//sets desired name for game
void gameobject::set_name(string name1)
{
name = name1;
}
//displays the name of the game
string gameobject::get_name()
{
return(name);
}
//presents a menu to choose type of game
void gameobject::set_type(int type_of_game)
{
type = type_of_game;
}
//prints the type of game chosen
string gameobject::get_type()
{
if (type == 0)
{
type_name = "cartridge";
return(type_name);
}
else if (type == 1)
{
type_name = "CD";
return(type_name);
}
else if (type == 2)
{
type_name = "DVD";
return(type_name);
}
else if (type == 3)
{
type_name = "BR";
return(type_name);
}
else if (type == 4)
{
type_name = "download";
return(type_name);
}
}
//sets the buying value of game
void gameobject::set_buy_value(float buy_game)
{
buy_value = buy_game;
}
//displays the buying value for game
float gameobject::get_buy_value()
{
return(buy_value);
}
//sets market value
void gameobject::set_market_value(float market_price)
{
market_value = market_price;
}
//displays market value
float gameobject::get_market_value()
{
return(market_value);
}
//sets model year of the game
void gameobject::set_year(int year1)
{
year = year1;
}
//displays model year
int gameobject::get_year()
{
return(year);
}
I have not written the code for print or total value. But I am mostly worried about getting the gameobject gameobjs[10] array to work. I have no idea how to fill the array and it is supposed to be filled with the game info after I add a game. help?
You can do this in void gamelist::add_game()
test.set_id_num(id);
this->gameobjs[0].set_id_num(id);
Then what you can do is to execute the statements present in add_game() in a loop, and add 10 gameobjects.
Try this, it will help you to add 10 games for 1 gamelist object
int id;
string name_game;
int type_game;
int buy;
int market;
int year_game;
for(int i = 0; i <10; i++)
{
cout << "Please enter an id number for the game: ";
cin >> id;
this->gameobjs[i].set_id_num(id);
cout << "Please enter a name for the game: ";
cin.ignore();
getline(cin, name_game);
cin.ignore();
this->gameobjs[i].set_name(name_game);
cout << "There are four types of games." << endl;
cout << " 0. Cartridge " << endl;
cout << " 1. CD " << endl;
cout << " 2. DVD " << endl;
cout << " 3. BR " << endl;
cout << " 4. Download " << endl;
cout << "Which type do you want to set for the game (enter number)? ";
cin >> type_game;
this->gameobjs[i].set_type(type_game);
cout << "Please set a buying value for the game: ";
cin >> buy;
this->gameobjs[i].set_buy_value(buy);
cout << "Please set the market value of the game: ";
cin >> market;
this->gameobjs[i].set_market_value(market);
cout << "What is the model year of the game? ";
cin >> year_game;
this->gameobjs[i].set_year(year_game);
}
I have to write a program for an array based database that will allow the user to enter new data, update existing data, delete entries and view a list of the entries. The requirements are a structure called DATE, a structure called CustData that holds the user data, an array of type CustData with a size of 10 and requires an individual function for entering, updating, deleting and displaying the customer data. It also needs to use a while loop to initialize each index in the array with everything initialized to 0. I have a rough program written but the more I work on it the more I feel like I am doing it completely wrong. So far I have it working to the point that it lets me add multiple entries without overwriting previous ones, but I can't seem to be able to limit the number of entries I can input. I also have the displaying of entries correct. Any help that could be offered is greatly appreciated, below is my program so far, with some of the data input sections commented out to make testing it easier. My apologies for leaving this out, this is in C++, written with visual studio 2013.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
struct Date
{
int month,
day,
year;
};
struct cust
{
int ID;
string name;
string address;
string city;
string state;
string zip;
string phone;
double balance;
Date lastpayment;
};
const int SIZE = 10;
int menuchoice;
int num = 0;
int i;
void showmenu();
void funcentercustdata(cust[], int);
void funcupdatecustdata();
void funcdeletecustdata();
void funcdisplaycustdata(cust[], int);
cust custdb[SIZE];
int main()
{
cout << "Welcome to Michael's Marvelous Database Contrabulator!\n";
cout << setw(10) << "Customer Database\n\n\n";
showmenu();
int index;
for (index = 0; index < SIZE; index++)
{
custdb[index].ID = 0;
custdb[index].name = "";
custdb[index].address = "";
custdb[index].city = "";
custdb[index].state = "";
custdb[index].zip = "";
custdb[index].phone = "";
custdb[index].balance = 0.00;
custdb[index].lastpayment.month = 0;
custdb[index].lastpayment.day = 0;
custdb[index].lastpayment.year = 0;
}
return 0;
}
void showmenu()
{
cout << "\n\n1) Enter new customer data.\n";
cout << "2) Update customer data.\n";
cout << "3) Delete customer data.\n";
cout << "4) Display Customer data.\n";
cout << "5) Quit the program.\n\n";
cout << "Please enter your choice: ";
cin >> menuchoice;
do
{
switch (menuchoice)
{
case 1:
funcentercustdata(custdb, SIZE);
showmenu();
break;
case 2:
funcupdatecustdata();
showmenu();
break;
case 3:
funcdeletecustdata();
showmenu();
break;
case 4:
funcdisplaycustdata(custdb, SIZE);
showmenu();
break;
case 5:
cout << "Thank you and have a nice day!\n";
break;
default:
cout << "Please enter a correct choice\n";
cin >> menuchoice;
break;
}
} while (menuchoice != 5);
}
void funcentercustdata(cust custinfo[], int size)
{
if (custinfo[i].ID != 0)
{
i++;
cout << "\n\nEnter ID: ";
cin >> custinfo[i].ID;
cout << "Enter name: ";
cin.ignore(0);
cin >> custinfo[i].name;
/* cout << "Enter address: ";
cin.ignore(0);
cin>>custinfo[i].address;
cout << "Enter city: ";
cin.ignore(0);
cin>>custinfo[i].city;
cout << "Enter state: ";
cin.ignore(0);
cin>>custinfo[i].state;
cout << "Enter zip: ";
cin.ignore(0);
cin>>custinfo[i].zip;
cout << "Enter phone number (###-###-####): ";
cin.ignore(0);
cin>>custinfo[i].phone;
cout << "Enter balance: ";
cin >> custinfo[i].balance;
cout << "Enter last payment (mo day year, e.g. 11 17 2014): ";
cin >> custinfo[i].lastpayment.month >> custinfo[i].lastpayment.day
>> custinfo[i].lastpayment.year;
cin.ignore(1);
// }*/
cout << "Customers successfully added.\n";
}
else if (custinfo[i].ID != 0 && custinfo[i].ID >= 4)
{
cout << "No further inputs allowed\n";
}
else
{
cout << "\n\nEnter ID: ";
cin >> custinfo[i].ID;
cout << "Enter name: ";
cin.ignore(0);
cin >> custinfo[i].name;
/* cout << "Enter address: ";
cin.ignore(0);
cin>>custinfo[i].address;
cout << "Enter city: ";
cin.ignore(0);
cin>>custinfo[i].city;
cout << "Enter state: ";
cin.ignore(0);
cin>>custinfo[i].state;
cout << "Enter zip: ";
cin.ignore(0);
cin>>custinfo[i].zip;
cout << "Enter phone number (###-###-####): ";
cin.ignore(0);
cin>>custinfo[i].phone;
cout << "Enter balance: ";
cin >> custinfo[i].balance;
cout << "Enter last payment (mo day year, e.g. 11 17 2014): ";
cin >> custinfo[i].lastpayment.month >> custinfo[i].lastpayment.day
>> custinfo[i].lastpayment.year;
cin.ignore(1);
// }*/
cout << "Customers successfully added.\n";
}
}
void funcupdatecustdata()
{
cout << "insert function 2\n\n";
}
void funcdeletecustdata()
{
cout << "insert function 3\n\n";
}
void funcdisplaycustdata(cust custinfo[], int size)
{
for (int i = 0; i < size; i++)
{
if (custinfo[i].ID == 0)
cout << " ";
else if (custinfo[i].ID != 0)
{
cout << "\n\nClient ID: " << custinfo[i].ID << endl;
cout << "Client name: " << custinfo[i].name << endl;
/* cout << "Client address: " << custinfo[i].name << endl;
cout << "Client city: " << custinfo[i].name << endl;
cout << "Client state: " << custinfo[i].name << endl;
cout << "Client zip: " << custinfo[i].name << endl;
cout << "Client phone: " << custinfo[i].name << endl;*/
cout << "Client balance: " << custinfo[i].balance << endl;
cout << "Client last deposit: " << custinfo[i].lastpayment.month << "/" <<
custinfo[i].lastpayment.day << "/" << custinfo[i].lastpayment.year << endl;
}
}
}
You've asked multiple questions concerning the issues in your program. So I will look at the first question:
I can't seem to be able to limit the number of entries I can input
First, your code has some fundamental flaws. One flaw is the repeated calling of showmenu() while you're in the showmenu() function. This is a recursive call, and is totally unnecessary. Imagine if your program or similar program that was structured this way had to be running 24 hours a day, and there were thousands of entries added. You will evenutally blow out the stack with all the recursive calls. So this has to be fixed.
Second, showmenu(), at least to me, should do what it says, and that is "show the menu". It should not be processing input. Do the processing of input in a separate function.
Here is a more modularized version of the program:
#include <iostream>
void processChoice(int theChoice);
void showmenu();
void addCustomer();
void deleteCustomer();
int getMenuChoice();
int customerCount = 0;
int main()
{
cout << "Welcome to Michael's Marvelous Database Contrabulator!\n";
cout << setw(10) << "Customer Database\n\n\n";
int choice = 0;
do
{
showmenu();
choice = getMenuChoice();
if (choice != 5)
processChoice(choice);
} while (choice != 5);
}
void showmenu()
{
cout << "\n\n1) Enter new customer data.\n";
cout << "2) Update customer data.\n";
cout << "3) Delete customer data.\n";
cout << "4) Display Customer data.\n";
cout << "5) Quit the program.\n\n";
}
int getMenuChoice()
{
int theChoice;
cout << "Please enter your choice: ";
cin >> theChoice;
return theChoice;
}
void processChoice(int theChoice)
{
switch (theChoice)
{
case 1:
addCustomer();
break;
//...
case 3:
deleteCustomer();
break;
}
}
void addCustomer()
{
if ( customerCount < 10 )
{
// add customer
// put your code here to add the customer
//...
// increment the count
++customerCount;
}
}
void deleteCustomer()
{
if ( customerCount > 0 )
{
// delete customer
--customerCount;
}
}
This is the basic outline of keeping track of the number of customers. Code organization and modularity is the key. The count of the current number of entries is either incremented or decremented wihin the addCustomer and deleteCustomer functions. Also note the test that is done in add/deleteCustomer().
In the main() function, note the do-while loop and the way it is set up. The showMenu function shows itself, the getMenuChoice function gets the choice and returns the number that was chosen.
If the choice is not 5, process the request. If it is 5, then the while part of the do-while kicks you out of the processing, otherwise you start back at the top (showMenu, getMenuChoice, etc). This avoids the recursive calls that your original code was doing.