array based database not working correctly - c++

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.

Related

Trying to incorporate void functions into switch statements

I'm a novice coding student and trying to create a menu using structs, functions, and switch statements to make a mini database for a class assignment. I'm trying to implant the functions into the switch statements.
I'm getting errors on lines 87 and 137 and I'm not sure where I'm going wrong. Any help, explanation, or correction is much appreciated.
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
using namespace std;
// Jaret Clark
// Week 3 Interactive Assignment
// INT 499
// Prof. Joseph Issa
// 03/31/2022
struct EZTechMovie {
string name;
string *cast[10];
string rating;
};
void displaymovie(EZTechMovie movie, int cast_num) {
int i;
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
cout << "Your entry:\n";
//Movies
cout << endl;
cout << "Movie TITLE: " << movie.name;
cout << endl;
//Movie rating
cout << "Movie Rating: " << movie.rating;
cout << endl;
//Cast name
cout << "Main Cast Members: \n";
//loop for cast members ~ stores in array
for (int i = 0; i < cast_num; ++i) {
cout << movie.cast[i];
cout << endl;
}
}
void mainmenu() {
string movie_input;
int m;
cout << endl;
cout << "Would you like to store movies into database? (yes or no) ";
getline(cin, movie_input);
cout << endl;
if (movie_input == "yes") {
string cont;
string cast_name;
int x, m, n, i, cast_num;
EZTechMovie moviedb[100];
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
for (n = 0; n < 100; n++) {
cout << "Movie Title: ";
getline(cin, moviedb[n].name);
cout << endl;
cout << "Movie rating: ";
getline(cin, moviedb[n].rating);
cout << endl;
cout << "How many cast do you want to enter? ";
cin >> cast_num;
cout << endl;
cin.ignore();
for (i = 0; i < cast_num; i++) {
cout << "Cast name: First and Last name: ";
getline(cin, moviedb[n].cast[i]);
cout << endl;
}
cout << endl;
displaymovie(moviedb[n], cast_num);
cout << endl;
cout << "Add more movies? (yes or no) ";
getline(cin, cont);
if (cont == "no") {
break;
}
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
}
}
else if (movie_input == "no") {
return;
}
else {
cout << "INVALID Input";
mainmenu();
}
}
// menu
void movieMenu() {
int choice;
EZTechMovie movie;
do {
cout << "***********************Welcome to EZTechMovie Movie Entry Menu***********************" << endl;
cout << "Press 1 to Enter Movie Info - Name, Cast Members, and Rating.\n";
cout << "Press 2 to Retrieve movie info recently entered.\n";
cout << "Press 3 To Quit program.\n";
// evaluate menu options in switch case
switch (choice) {
case 1:
mainmenu();
break;
case 2:
displaymovie(EZTechMovie movie, int cast_num);
break;
case 3:
cout << "Thank you and Goodbye!";
break;
default:
cout: "Invalid Selection. Try again!\n";
}
//get menu selection
cin >> choice;
} while (choice != 3);
}
int main() {
movieMenu();
}
Regarding the error on line 87 (getline(cin, moviedb[n].cast[i]);) :
moviedb[n].cast[i] is a std::string*, not std::string like you might have meant.
A quick compilation fix would be to use:
getline(cin, *(moviedb[n].cast[i]));
i.e. dereference the pointer.
However - this code raises other design/programming issues:
Why do you use std::string* and not std::string in the first place.
Why do you use C style array instead of std::vector (or std::array if you can commit to the size). This is relevant for both: string *cast[10]; and EZTechMovie moviedb[100];

Checking integer for input validation of a node

I'm trying to do my input validation where I have already predefined data in my program. When I want the user to key in a new employee id, I want it to check whether that ID is already in the database, if yes, how do i keep looping it until the user types in an id which is not in the database?
struct employee {
int empNo, salary, performance;
string name, phoneNo, address, depNo, depName;
employee* next;
employee* previous;
} *temp, *head, *tail, *newhead, *newtail, *newnode;
void validate()
{
cout << "Input not accepted, please try again!" << endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
}
int main()
{
int choice = 1;
int num, salary, performance = 0;
string name, hpnum, depName, depNo, address;
bool execute = true;
insertemployeerecord(0002, "Ethan Tan", 16000, "017-2399193", "Kuala Lumpur, Malaysia", "F001", "Finance", 2);
insertemployeerecord(0003, "Nikshaen Kumar", 15000, "016-9188131", "Los Angeles, California", "A001", "Audit", 3);
insertemployeerecord(0001, "Koughen Mogan", 17500, "014-1233241", "Los Angeles, California", "F001", "Finance", 4);
while (execute)
{
cout << "..........................................................." << endl;
cout << " EMERGE EMPLOYEE SYSTEM " << endl;
cout << "..........................................................." << endl;
cout << endl;
cout << "1. Add an Employee Record" << endl;
cout << "2. Display All Records" << endl;
cout << "3. Search by Employee ID" << endl;
cout << "4. Search by Employee overall performance" << endl;
cout << "5. Sort and display by Employee ID in ascending order" << endl;
cout << "6. Sort and display by Employee Salary in ascending order " << endl;
cout << "7. Sort and display by Employee Overall Performance in ascending order " << endl;
cout << "8. Modify an Employee Record" << endl;
cout << "9. Delete an Employee Record" << endl;
cout << "10. Calculate salary package of an employee" << endl;
cout << "11. Exit" << endl;
cout << endl << endl;
cout << "Select your option: ";
cin >> choice;
if (choice == 1)
{
system("cls");
cout << "Enter employee number: ";
cin >> num;
while (!cin >> num) //to see if user types anything besides number
{
validate();
cout << "Enter employee number: ";
cin >> num;
}
temp = head;
bool verify = true;
if (temp != NULL)
{
while (temp->empNo != num)
{
temp = temp->next;
if (temp == NULL)
{
verify = false;
break;
}
}
while (verify == true) //if the user types an id that is found in the database
{
validate();
cout << "Employee found in database!" << endl;
cout << "Enter employee number: " << endl;
cin >> num;
}
if (verify == false)
{
cin.get();
}
}
cout << endl;
cout << "Enter employee name: ";
getline(cin, name);
As you can see, my output can detect if there is an alphabet being typed and also if the user types an id thats already in the database, but when I type a new id, example being 4, the system still says it detects from the database
Enter employee number: a
Input not accepted, please try again!
Enter employee number: 1
Input not accepted, please try again!
Employee found in database!
Enter employee number:
2
Input not accepted, please try again!
Employee found in database!
Enter employee number:
3
Input not accepted, please try again!
Employee found in database!
Enter employee number:
4
Input not accepted, please try again!
Employee found in database!
You can do something like this :
int enter_employee_number() {
int number;
do{
cout << "Enter employee number: ";
cin >> number;
bool fail = cin.fail();
if(fail)
cout << "Input not accepted, please try again!" << endl;
} while (fail);
return number;
}
string enter_employee_name() {
string name;
do{
cout << "Enter employee name: ";
cin >> name;
bool fail = cin.fail();
if(fail)
cout << "Input not accepted, please try again!" << endl;
} while (fail);
return name;
}
employee get_employee(int number) {
// retrieve your employee and return it.
}
int main() {
// other part of your code
if (choice == 1) {
system("cls");
while(true) {
int empNo = enter_employee_number();
employee emp = get_employee();
if (emp != nullptr) {
cout << "Employee found in database!" << endl;
string empName = enter_employee_name();
// call method that use empName
}
else {
cout << "Employee not found in database!" << endl;
}
cout << endl;
}
}
}
Recommended way of input validation is via getting everything in a string, like define string inputLine and use std::getline() and then parsing it using std::istringstream(inputLine). If you want to continue till validation succeeds, put below code in loop.
if ( stringStream >> ID >> std::ws && stringStream.get() == EOF)
//At this point you have Employee Id in ID variable , Now you can do database check.
if(validate(ID)) // if validation succeeds.
break; // Break out of loop, otherwise continue till you get correct input.

Cant create array of objects in c++

#include <iostream>
using namespace std;
class Bank
{
private:
char account_holder[50];
int accnum;
int balance;
int dep_amount;
int with_amount;
public:
void getdata();
void putdata();
void deposit();
void withdraw();
};
void Bank::getdata()
{
cout << "Enter the account holders name : " << endl;
cin >> account_holder;
cout << "Enter the account number : " << endl;
cin >> accnum;
cout << "Enter the balance in your account : " << endl;
cin >> balance;
}
void Bank::putdata()
{
cout << "The account holders name is : " << account_holder << endl;
cout << "The account number is : " << accnum << endl;
cout << "The balance in your account is : " << balance << endl;
cout << endl;
}
void Bank::deposit()
{
cout << "Enter the amount to be deposited : " << endl;
cin >> dep_amount;
balance = balance + dep_amount;
cout << "Your current balance is : " << balance << endl;
}
void Bank::withdraw()
{
cout << "Enter the amount to be withdrawn : " << endl;
cin >> with_amount;
balance = balance - with_amount;
cout << "Your current balance is : " << balance << endl;
}
int main(){
Bank ram[5];
int ch, a, n, acc;
cout << "How you account holders you want to add : " << endl;
cin >> n;
do
{
cout << "Enter 1.To insert data" << endl;
cout << "Enter 2.To display data" << endl;
cout << "Enter 3.To deposit amount" << endl;
cout << "Enter 4.To withdraw amount" << endl;
cout << "Enter your choice : " << endl;
cin >> ch;
switch (ch)
{
case 1:
for (int i = 0; i < n;i++)
ram[i].getdata();
break;
case 2:
for (int i = 0; i < n; i++)
ram[i].putdata();
break;
case 3:
cout << "Enter the account you want to deposit money into " << endl;
cin >> acc;
for (int i = 0; i < n; i++)
ram[acc].deposit();
break;
case 4:
for (int i = 0; i < n; i++)
ram[i].withdraw();
break;
}
cout << "Enter 6. To Continue" << endl;
cin >> a;
} while (a == 6);
return 0;
}
I am using this code and my problem is that when I want to deposit or withdraw some amount,I want to take account number from user and then deposit/withdraw amount from that object only. How can I enter that object using account number taken from user? Please Help.
Unfortunately you have a few problems with your code and your logic. Let us address them one by one:
1- You are using a char array to keep the account holder name. If you are programming C++ you should be using std::string in almost all situations.
2- You are using unconventional names for your public methods in Bank and this is a bad habit at best.
More specifically, getdata() is a poor method name because mehtods that start with "get" should generally be reserved for methods that return a single field that belongs to the class instance. For example int getAccountNumber()
your getdata() should be fillInData() follow me?
3- You are using an array of Bank in your main in order to hold the number of accounts. While this is possible, it is far from ideal. You should strive to use std::vector when it makes sense (like here). Why is a naked array bad? because if you use an array the size of the array has to be known at compile time, which means you can not increase the number of accounts when the program is running. If you declare a big array on the stack, you may have a lot of space but you are wasting precious stack space.
4- The logic you have employed for your "input loop" is messy and hard to navigate. The design can be improved significantly to improve readability and maintainability of code. Consider the fact that you declare and read int n; but you never use it in the program.
5- Compile time errors from undeclared variables like i
6- Logically and semantically incorrect program behaviour: you iterate through a for loop of all records and withdraw/deposit in ALL records, instead of selecting the one you need.
7- No bounds checking of any kind. Asking for bad things to happen.
I am giving you a minimally adjusted code that makes sense. Note that this is still not the ideal way to accomplish this task but at least it does not have syntax and semantic errors:
int Bank::getAccountNumber()
{
return this->accnum;
}
int getIndexByAccountNumber(Bank allAccounts[], int size, int accountNumber) //returns index or -1 in case account number is not found
{
for(int i=0; i<size; ++i)
{
if (allAccounts[i].getAccountNumber()==accountNumber) return i;
}
return -1;
}
int main(){
const int NumberOfAccounts=5;
Bank ram[NumberOfAccounts];
int nextIndex=0;
int ch, a, acc;
while(true)
{
cout << "Enter 1.To insert data for a new account" << endl;
cout << "Enter 2.To display data of all existing accounts" << endl;
cout << "Enter 3.To deposit to an existing account" << endl;
cout << "Enter 4.To withdraw from an existing account" << endl;
cout << "Enter 5.To terminate program" << endl;
cout << "Enter your choice : " << endl;
cin >> ch;
if(ch==1)
{
if(nextIndex>=NumberOfAccounts)
{
cout<<"error: you have space for only "<<NumberOfAccounts<<" accounts! terminating program";
break;//breaks out of while loop
}
ram[nextIndex].getdata();//gets all fields for the account
nextIndex++;
}
else if(ch==2)
{
cout << "showing information for all accounts: " << endl;
for (int i = 0; i < nextIndex; i++) ram[i].putdata();
cout<<"\n\n";
}
else if(ch==3)
{
cout << "Enter the account you want to deposit money into " << endl;
cin >> acc;
int index = getIndexByAccountNumber(ram,NumberOfAccounts,acc);
if(index==-1)
{
cout<<"the account number you entered could not be found, terminating program!\n";
break;//breaks out of while loop
}
ram[index].deposit();
}
else if(ch==4)
{
cout << "Enter the account you want to withdraw from " << endl;
cin >> acc;
int index= getIndexByAccountNumber(ram,NumberOfAccounts,acc);
if(index==-1)
{
cout<<"the account number you entered could not be found, terminating program!\n";
break;//breaks out of while loop
}
ram[index].withdraw();
}
else if(ch==5)
{
break;
}
else
{
cout<<"you entered invalid choice\n";
}
}//end of while loop
return 0;
}
cout << "Enter the account you want to deposit money into " << endl;
cin >> acc;
for (int i = 0; i < n; i++)
ram[acc].deposit();
break;
Here is your problem - wrong index variable. Try "i"
In your case 3 you use a different iterator than the rest. Is this by design or what? I am missing the purpose of using acc instead of i. This might be your problem, unless I am overlooking your purpose for using it.

I am creating a game tool using classes and functions. I need to store the game info in an index of an array but dont know how?

//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);
}

C++ Address Book Array and Textfile

Sorry for the lack of previous explanation to my school's assignment. Here's what I'm working with and what I have / think I have to do.
I have the basic structure for populating the address book inside an array, however, the logic behind populating a text file is a bit beyond my knowledge. I've researched a few examples, however, the implementation is a bit tricky due to my novice programming ability.
I've gone through some code that looks relevant in regard to my requirements:
ifstream input("addressbook.txt");
ofstream out("addressbook.txt");
For ifstream, I believe implementing this into the voidAddBook::AddEntry() would work, though I've tried it and the code failed to compile, for multiple reasons.
For ostream, I'm lost and unsure as to how I can implement this correctly. I understand basic file input and output into a text file, however, this method is a bit more advanced and hence why I'm resorting to stackoverflow's guidance.
#include <iostream>
#include <string.h> //Required to use string compare
using namespace std;
class AddBook{
public:
AddBook()
{
count=0;
}
void AddEntry();
void DispAll();
void DispEntry(int i); // Displays one entry
void SearchLast();
int Menu();
struct EntryStruct
{
char FirstName[15];
char LastName[15];
char Birthday[15];
char PhoneNum[15];
char Email[15];
};
EntryStruct entries[100];
int count;
};
void AddBook::AddEntry()
{
cout << "Enter First Name: ";
cin >> entries[count].FirstName;
cout << "Enter Last Name: ";
cin >> entries[count].LastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
cout << "Enter Email: ";
cin >> entries[count].Email;
++count;
}
void AddBook::DispEntry(int i)
{
cout << "First name : " << entries[i].FirstName << endl;
cout << "Last name : " << entries[i].LastName << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
}
void AddBook::DispAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DispEntry(i);
}
void AddBook::SearchLast()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].LastName) == 0)
{
cout << "Found ";
DispEntry(i);
cout << endl;
}
}
}
AddBook AddressBook;
int Menu()
{
int num;
bool BoolQuit = false;
while(BoolQuit == false)
{
cout << "Address Book Menu" << endl;
cout << "(1) Add A New Contact" << endl;
cout << "(2) Search By Last Name" << endl;
cout << "(3) Show Complete List" << endl;
cout << "(4) Exit And Save" << endl;
cout << endl;
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
return 0;
}
int main (){
Menu();
return 0;
}
As it currently stands, I'm still stuck. Here's where I believe I should start:
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
//save first name
//save last name
//save dob
//save phone number
//save email
//exit
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
Somehow, during menu option 4 the array should dump the data into a .txt file and arrange it in a way that it can be easily imported upon reloading the program. I'm a little confused as to how I can store the array data from each character array into a .txt file.
Well first, if the input is coming from the file input, then instead of doing cin >> x you would have to do input >> x. If it's coming from standard input (the keyboard), then you can use cin.
Also, your else if statement should be something like this:
while (true)
{
// ...
else if (num == 4)
{
for (int i = 0; i < AddressBook.count; ++i)
{
AddBook::EntryStruct data = AddressBook.entries[i];
out << data.FirstName << " " << data.LastName
<< std::endl
<< data.Birthday << std::endl
<< data.PhoneNum << std::endl
<< data.Email;
}
}
break;
}