I have two text files and the Load function transfers the data from both text files to a single struct (Employee emp[length]) with a const length of 2001. This is because there are 2000 employee details in the text file.
After loading the data into struct, I wanted to search and display employee data using the Select function.
The user will be prompted to choose which employee attribute and keyword that is going to be used for searching. However, I realize that I cannot return a struct(emp[i]) or a string value(emp[i].empId). It will prompt out an error saying
access violation reading location 0x00D2C000
However, I am able to display the string value(emp[i].empId) using cout.
May I know why can I cout the string value but not return it?
Thank you for your help in advance and sorry for my poor English.
const int length = 2001;
struct Employee {
string empId;
string dOB;
string height;
string weight;
string yrOfWork;
string salary;
string allowance;
string name;
string country;
string designation;
string gender;
string lvlOfEdu;
};
Employee emp[length];
void Load();
Employee Select(int k, string s, int c);
int main() {
bool quit = false;
int option;
while (quit != true) { //loop the program unless 7 is chosen
Load();
cout << "1. Add" << endl; //
cout << "2. Delete" << endl;
cout << "3. Select" << endl;
cout << "4. Advanced Search" << endl;
cout << "5. Standard Deviation" << endl;
cout << "6. Average" << endl;
cout << "7. Quit" << endl;
cout << "Please key in an option: ";
cin >> option;
system("cls"); //to refresh the screen
switch (option) {
case 3: {
int search;
string key;
cout << "1. Employee ID" << endl;
cout << "2. Date of Birth" << endl;
cout << "3. Height" << endl;
cout << "4. Weight" << endl;
cout << "5. Years of Working" << endl;
cout << "6. Basic Salary" << endl;
cout << "7. Allowance" << endl;
cout << "8. Employee Name" << endl;
cout << "9. Country" << endl;
cout << "10. Designation" << endl;
cout << "11. Gender" << endl;
cout << "12. Level of Education" << endl;
cout << "Select By: ";
cin >> search;
cout << "Enter keyword: ";
cin >> key;
for (int i = 0; i < length; i++) {
cout << Select(search, key, i).empId;
}
system("pause");
system("cls");
break;
}
}
}
}
Employee Select(int s, string k, int c) {
int result;
int i = c;
switch(s) {
case 1:
result = emp[i].empId.find(k);
if (result >= 0) {
return emp[i];
}
break;
}
}
void Load() {
ifstream inFigures;
inFigures.open("profiles_figures.txt");
ifstream inWords;
inWords.open("profiles_words.txt");
if (inFigures.is_open()) {
int i = 0;
while (!inFigures.eof()) {
inFigures >> emp[i].empId;
inFigures.ignore();
inFigures >> emp[i].dOB;
inFigures.ignore();
inFigures >> emp[i].height;
inFigures.ignore();
inFigures >> emp[i].weight;
inFigures.ignore();
inFigures >> emp[i].yrOfWork;
inFigures.ignore();
inFigures >> emp[i].salary;
inFigures.ignore();
inFigures >> emp[i].allowance;
inFigures.ignore();
i++;
}
}
//inFigures.close();
if (inWords.is_open()) {
int i = 0;
while (!inWords.eof()) {
getline(inWords, emp[i].name);
getline(inWords, emp[i].country);
getline(inWords, emp[i].designation);
inWords >> emp[i].gender;
inWords.ignore();
inWords >> emp[i].lvlOfEdu;
inWords.ignore();
i++;
}
}
//inWords.close();
}
The main problem I think is, what do you return if Select doesn't find anything? The function is supposed to return an employee. You could have a special Employee with a nonsensical empId (e.g. -1) to indicate this, and change
for (int i = 0; i < length; i++)
{
cout << Select(search, key, i).empId;
}
to
for (int i = 0; i < length; i++)
{
Employee selected = Select(search, key, i);
if (selected.empId != -1)
{
cout << Select(search, key, i).empId;
}
}
Alternatively you could alter the Select function so that it returns a pointer Employee * and then return nullptr if there is no match. That is
Employee* Select(int s, string k, int c)
{
int result;
int i = c; // why not just use c directly? Or change the argument to int i?
switch(s)
{
case 1:
result = emp[i].empId.find(k);
if (result >= 0)
{
return &emp[i]; // note taking address, could also write emp + i
}
break; // don't need this with no further cases
}
return nullptr; // reached if no match above
}
Followed later by
for (int i = 0; i < length; i++)
{
Employee* selected = Select(search, key, i);
if (selected != nullptr)
{
cout << Select(search, key, i)->empId; // not pointer indirection
}
}
Really you'd probably want to return a const Employee const*, but that's another topic.
Yet another option is having Select throw an exception if it doesn't find anything, and placing the call to Select(search, key, i); in a try .. catch block. I generally prefer not to use exceptions for control flow like this, but it is another method.
Related
For one of my options, I had to add a row of data to my struct array, I was able to update the array but it does not update the actual array. So I am trying to update my struct array by passing it as a reference. I placed the '&' sign before the name of the variable, but all my indexes within the function errored.. I'm still a newbie to programing and I'm not "allowed " to use any vectors according to my Professor. . I looked online and placed the '&' on the function name as well as on the prototype. I also changed it from void to the "data type" to return the updated array, but no luck... I hope this comes out clear....
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
struct Data {
string first_name;
string last_name;
int employee_id;
string phone_number;
};
void readFile( ifstream& , string, Data [],int&);
void getEmployeeDetail(Data [], int&);
void getEmployeeLast(Data [], int&);
Data getAddEmployee(Data &, int&);
void getRemoveEmployee();
void getManagerOnly();
void getStaffOnly();
const int SIZE = 15;
Data employee[SIZE];
int main() {
ifstream inputFile;
ofstream outputFile;
int count = 0;
int selection;
const int EMPLOYEE_DETAIL = 1,
EMPLOYEE_LAST = 2,
ADD_EMPLOYEE = 3,
REMOVE_EMPLOYEE = 4,
MANAGER_ONLY = 5,
STAFF_ONLY = 6,
QUIT = 7;
readFile( inputFile ,"employeeData.txt", employee,count);
do {
cout << "\t Please select your option.\n"
<< "1. List all employee details\n"
<< "2. List employee by last name\n"
<< "3. Add a new employee\n"
<< "4. Remove an employee\n"
<< "5. Show all managers only\n"
<< "6. Show all staff only\n"
<< "7. Quit\n"
<< "Please enter your selection.\n" << endl;
cin >> selection;
while (selection < EMPLOYEE_DETAIL || selection > QUIT) {
cout << " Pleasse enter a valid selection.\n";
cin >> selection;
}
switch (selection) {
case EMPLOYEE_DETAIL:
getEmployeeDetail(employee,count);
break;
case EMPLOYEE_LAST:
getEmployeeLast(employee, count);
break;
case ADD_EMPLOYEE:
getAddEmployee(employee, count);
break;
case REMOVE_EMPLOYEE:
getRemoveEmployee();
break;
case MANAGER_ONLY:
getManagerOnly();
break;
case STAFF_ONLY:
getStaffOnly();
break;
case QUIT:
cout << "Program ending\n";
break;
}
} while (selection != QUIT);
system("pause");
return(0);
}
void readFile(ifstream& inputFile, string data, Data employee[],int &count) {
inputFile.open(data);
if (!inputFile) {
cout << " Error in opening file\n";
exit(1);
}
else {
while (!inputFile.eof()) {
inputFile >> employee[count].first_name;
inputFile >> employee[count].last_name >> employee[count].employee_id >> employee[count].phone_number;
count++;
}
inputFile.close();
}
return;
};
void readFile(ifstream& inputFile, string data, Data employee[],int &count) {
inputFile.open(data);
if (!inputFile) {
cout << " Error in opening file\n";
exit(1);
}
else {
while (!inputFile.eof()) {
inputFile >> employee[count].first_name;
inputFile >> employee[count].last_name >> employee[count].employee_id >> employee[count].phone_number;
count++;
}
inputFile.close();
}
return;
};
void getEmployeeDetail( Data employee[], int& count) {
cout << "Firt Name" << "\t" << "Last Name " << "\t" << "Employee ID " << "\t" << "Phone Number \n";
cout << "--------------------------------------------------------------------------\n";
for(int i =0; i < count; i++)
cout <<employee[i].first_name<<"\t\t"<<employee[i].last_name<<"\t\t"<<employee[i].employee_id<<"\t\t"<<employee[i].phone_number<< "\n ";
cout << endl;
}
void getEmployeeLast(Data employee[], int& count) {
string searchName;
cout << "Please enter the last name of the employee you want to search for.\n";
cin >> searchName;
/*
for (int i = 0; i < count; i++)
if (searchName ==employee[i].last_name) {
cout << employee[i].last_name;
}
*/
string matchString = searchName;
for (int i = 0; i < count; i++) {
if (employee[i].last_name.find(matchString, 0) != std::string::npos) {
cout << employee[i].last_name << endl;
}
else {
cout << "No employee was located with that name.\n";
exit(1);
}
}
}
Data getAddEmployee(Data &employee, int& count) {
string firstName, lastName, phoneNumber;
int employeeID, size;
for (int i = 0; i < count; i++)
cout << employee[i].first_name << "\t\t\t" << employee[i].last_name << "\t\t" << employee[i].employee_id << "\t\t" << employee[i].phone_number << "\n ";
cout << endl;
cout << count <<"\n";
size = count + 1;
cout << size << "\n";
cout << "Please enter the new employee First Name.\n";
cin >> firstName;
cout << "Please enter the new employee Last Name.\n";
cin >> lastName;
cout << "Please enter the new employee's ID.\n";
cin >> employeeID;
cout << "Please enter the new employee Phone Number.\n";
cin >> phoneNumber;
employee[10].first_name = firstName;
employee[10].last_name = lastName;
employee[10].employee_id = employeeID;
employee[10].phone_number = phoneNumber;
for (int i = 0; i < size; i++) {
cout << employee[i].first_name << "\t\t\t" << employee[i].last_name << "\t\t" << employee[i].employee_id << "\t\t" << employee[i].phone_number << "\n ";
cout << endl;
}
return employee;
}
First of all, your naming could be better. Like employeeList instead employee to specify its a list/array of employee, also addEmployee instead of getAddEmployee.
Second, instead of pasting whole code, it's better to paste the relevant block of code based on your question to make it clearer.
The solution is, your array is basically already on global scope, you don't need to pass it. Can just directly modify the array.
struct Data {
string first_name;
string last_name;
int employee_id;
string phone_number;
};
void addEmployee();
const int SIZE = 15;
Data employeeList[SIZE];
int current = 0;
int main(){
Data emp1 = {"John", "Doe", 100, "12345"};
employeeList[0] = emp1;
current++;
addEmployee();
for(int i=0; i<current; i++){
Data emp = employeeList[i];
cout<<i+1<<" "<<emp.first_name<<" "<<emp.phone_number<<endl;
}
}
void addEmployee(){
Data emp2 = {"Sam", "Smith", 200, "67890"};
employeeList[current] = emp2;
current++;
}
Can try it here: https://onlinegdb.com/drhzEOpis
I have an assignment here that I've been working on for the past few hours and have been met with a problem. Whenever I compile and run the program in VS Code it throws me into an infinite loop where the text of the "menu" is printed repeatedly. I imagine this has something to do with the for(;;){ loop at the beginning of the menu.
I've deleted the for(;;){ statement at the beginning of the menu, and the continuous scrolling stopped, but I was unable to input any numbers (cases) and the program, essentially, just printed the menu and that was the end.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Student {
string name;
float GPA;
public:
string getName() const
{
return name;
}
float getGPA() const
{
return GPA;
}
void setName(string Name)
{
name = Name;
}
void setGPA(float gpa)
{
GPA = gpa;
}
Student(const string& name, float gpa)
: name(name)
, GPA(gpa)
{
}
Student()
{
}
void printDetails(Student s[], int n)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n; i++) {
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
float calcAverageGPA(Student s[], int n)
{
float avg = 0;
float sum = 0;
for (int i = 0; i <= n; i++) {
sum += s[i].getGPA();
}
avg = sum / n;
return avg;
}
float getGPAbyName(Student s[], int n, string name)
{
for (int i = 0; i <= n - 1; i++) {
if (s[i].getName() == name)
return s[i].getGPA();
}
return -1;
}
void showListByGPA(Student s[], int n, float gpa)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n - 1; i++) {
if (s[i].getGPA() > gpa)
;
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
};
int main()
{
int n = 0;
int ch;
Student s[50];
string name;
float GPA;
float avg = 0;
cout << "======================" << endl;
cout << "(1): Add a student" << endl;
cout << "(2): Print the details of a student" << endl;
cout << "(3): Get the GPA of a Student by name." << endl;
cout << "(4): Get names of students based on GPA." << endl;
cout << "(6): Quit the program." << endl;
cout << "Enter your option" << endl;
switch (ch) {
case '1':
cout << "\nEnter student's name" << endl;
cin >> name;
cout << "Enter GPA" << endl;
cin >> GPA;
s[n] = Student(name, GPA);
n++;
break;
case '2':
s[0].printDetails(s, n);
break;
case '3':
cout << "\nEnter the name of a student" << endl;
cin >> name;
GPA = s[0].getGPAbyName(s, n, name);
if (GPA == -1) {
cout << "\nStudent not found!" << endl;
}
else
cout << "\nGPA is: " << endl;
break;
case '4':
cout << "\nEnter GPA: " << endl;
cin >> GPA;
s[0].showListByGPA(s, n, GPA);
break;
case '5':
avg = s[0].calcAverageGPA(s, n);
cout << "\nAverage GPA: " << avg << endl;
break;
case '6':
exit(0);
}
}
I suspect the problem resides in main(). I included the prior blocks of the program in case they were necessary to provide any suggestions.
You obviously want to read in "ch".
You've also made this an int, and don't zero-initialize, which can cause some undefined behaviour if you don't set it beforehand.
The switch case should be
switch(X){
case 1:
// Code
break;
}
etc..
The difference is "1" or 1. It evaluates an enumeration value, instead of strings.
For safety: you might want to add a case default, which is common practice.
In the adding user section in the code below, I am unable to type any characters for the "Add another person?(y/n): " question. it just jumps back to entering age. How do I fix this?
I've tried to change ans into a string, implement a while loop to force the question to show up, and many other things. It just seems that nothing works and I've been trying it for the good part of two hours
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main()
{
char ans;
int people;
int option;
int count = 0;
struct data
{
string name;
int age;
char gender;
string comments;
}person[100];
// homescreen
homescreen:
cout << "Welcome to the Data Base!" << endl;
cout << endl;
// displaying all people
for (int list = 0; list < count; list++)
{
cout << list << ".) " << person[list].name << endl;
}
cout << endl;
cout << "[1] View Person" << endl;
cout << "[2] Add Person" << endl;
cout << "[3] Edit Person" << endl;
cout << "[4] Delete Person" << endl;
cout << "[5] Exit" << endl;
cout << "Choose Option: "; cin >> option;
// using options
while (option != 5)
{
if (option == 1)
{
view:
for (int list2 = 0; list2 < count; list2++)
{
cout << list2 << ".) " << person[list2].name << endl;
}
cout << endl;
cout << "Enter number of person you want: "; cin >> people;
system("cls");
cout << "Name: " << person[count].name << endl;
cout << "Age: " << person[count].age << endl;
cout << "Gender: " << person[count].gender << endl;
cout << "Comments: " << person[count].comments << endl << endl;
cout << "View another person?(y/n): "; cin >> ans;
if (ans == 'y')
{
system("cls"); goto view;
}
else if (ans == 'n')
{
system("cls"); goto homescreen;
}
}
if (option == 2)
{
add:
system("cls");
cout << "Name: "; cin >> person[count].name;
system("cls");
cout << "Age: "; cin >> person[count].age;
system("cls");
cout << "Gender(M/F/H): "; cin >> person[count].gender;
system("cls");
cout << "Comments: "; cin >> person[count].comments;
count++;
system("cls");
cout << "Add another person?(y/n): "; cin >> ans;
if (ans == 'y')
{
system("cls");
goto add;
}
else if (ans == 'n')
{
system("cls");
goto homescreen;
}
}
}
}
If you anybody can help me I'd be grateful
The goto statements in your code makes the program really good
spaghetti
structure and that is not
good.
Therefore, think instead of goto other options, such as infinite
while loop which will break once the user enters the n or moving
the code to the function.
Secondly what if you have not entered any persons and choosing the
option 1. You still output the attributes of the person as
count is initialized zero at least. Remember the attributes are
not initialized at this point. Accessing the uninitialized
variables will invoke undefined
behavior. Therefore,
provide a check (something like if(count > 0) )before you execute the code in option 1.
In addition to that, remember that
std::endl flushes the output buffer, and '\n' doesn't. Therefore, most of
the cases you might wanna use just
\n.
Last but not the least, use std::vector instead of the using C style arrays with some predefined size. What if the user has more than 100 inputs? The solution in C++ is std::vector, which can expand dynamically as its storage is handled automatically.
Following is a possible solution to your program, in which the comments will guide you through to the things that I mentioned above.
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
struct Data
{
std::string name;
int age;
char gender;
std::string comments;
Data(const std::string& n, int a, char g, const std::string& c) // provide a Constructor
:name(n), age(a), gender(g), comments(c)
{}
};
void debugMsg(const std::string& msg)
{
system("cls");
std::cout << "\n\n\t\t" << msg << "\n\n";
Sleep(3000);
}
int main()
{
std::vector<Data> person; // use std::vector to store the datas
while (true) // loop: 1
{
system("cls");
std::cout << "Welcome to the Data Base! \n\n";
std::cout << "[1] View Person\n";
std::cout << "[2] Add Person\n";
std::cout << "[3] Edit Person\n";
std::cout << "[4] Delete Person\n";
std::cout << "[5] Exit\n";
std::cout << "Choose Option: ";
int option; std::cin >> option;
switch (option) // use switch to validate the options
{
case 1:
{
while (true) // loop - 2 -> case 1
{
// if no data available to show -> just break the loop 2 and return to the outer loop(i.e, loop 1)
if (person.empty()) { debugMsg("No person available to show ....going to main manu...."); break; }
// otherwise: displaying all people
for (std::size_t index = 0; index < person.size(); ++index)
std::cout << index << ".) " << person[index].name << "\n";
std::cout << "\nEnter number of person you want: ";
std::size_t index; std::cin >> index;
// if the index is not valid -> just break the loop 2 and return to the outer loop(i.e, loop 1)
if (index < 0 || index >= person.size()) { debugMsg("Sorry, wrong index!... returning to the main menu......"); break; }
system("cls");
std::cout << "Name: " << person[index].name << std::endl;
std::cout << "Age: " << person[index].age << std::endl;
std::cout << "Gender: " << person[index].gender << std::endl;
std::cout << "Comments: " << person[index].comments << std::endl << std::endl;
std::cout << "View another person?(y/n): ";
char ans; std::cin >> ans;
if (ans == 'y') { system("cls"); continue; } // just continue looping
else if (ans == 'n') { break; } // this will break the loop 2 and return to the outer loop(i.e, loop 1)
else { debugMsg("Sorry, wrong option!... returning to the main menu......"); break; }
}
} break;
case 2:
{
while (true) // loop - 3 -> case 2
{
system("cls");
std::string name, comments; int age; char gender;
std::cout << "Name: "; std::cin >> name;
std::cout << "Age: "; std::cin >> age;
std::cout << "Gender(M/F/H): "; std::cin >> gender;
std::cout << "Comments: "; std::cin >> comments;
// simply construct the Data in person vector in place
person.emplace_back(name, age, gender, comments);
std::cout << "\n\nAdd another person?(y/n): ";
char ans; std::cin >> ans;
if (ans == 'y') { system("cls"); continue; }
else if (ans == 'n') { system("cls"); break; } // same as case 1
else { debugMsg("Sorry, wrong option!... returning to the main menu......"); break; }
}
} break;
case 3: { /*code*/ debugMsg("Sorry, Not implemented!... returning to the main menu......"); } break;
case 4: { /*code*/ debugMsg("Sorry, Not implemented!... returning to the main menu......"); } break;
case 5: return 0; // if its 5, just retun the main
default: break;
}
}
return 0;
}
As mentioned above, using "goto" is a bad style, so i would suggest structure your program a little. Below is my version.
Naturally, I did not add any checks and controls, the author will be able to do this on his own. But main logics should work. And, of course, it is better to use vector instead of static array.
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
enum options { OPT_VIEW = 1, OPT_ADD = 2, OPT_EDIT = 3, OPT_DELETE = 4, OPT_EXIT = 5 };
struct data
{
string name;
int age;
char gender;
string comments;
};
class App
{
private:
data person[100];
int count = 0;
public:
App();
void Run();
int HomeScreen();
void View();
void Add();
};
App::App() : count(0)
{}
void App::Run()
{
int option = HomeScreen();
while(option != OPT_EXIT)
{
switch(option)
{
case OPT_VIEW:
View();
break;
case OPT_ADD:
Add();
break;
}
option = HomeScreen();
}
}
int App::HomeScreen()
{
int option = 0;
cout << "Welcome to the Data Base!" << endl;
cout << endl;
// displaying all people
for(int list = 0; list < count; list++)
{
cout << list << ".) " << person[list].name << endl;
}
cout << endl;
cout << "[1] View Person" << endl;
cout << "[2] Add Person" << endl;
cout << "[3] Edit Person" << endl;
cout << "[4] Delete Person" << endl;
cout << "[5] Exit" << endl;
cout << "Choose Option: "; cin >> option;
return option;
}
void App::View()
{
char ans = 0;
do
{
int people = 0;
for(int list2 = 0; list2 < count; list2++)
{
cout << list2 << ".) " << person[list2].name << endl;
}
cout << endl;
cout << "Enter number of person you want: "; cin >> people;
system("cls");
cout << "Name: " << person[people].name << endl;
cout << "Age: " << person[people].age << endl;
cout << "Gender: " << person[people].gender << endl;
cout << "Comments: " << person[people].comments << endl << endl;
cout << "View another person?(y/n): "; cin >> ans;
}
while(ans == 'y');
system("cls");
}
void App::Add()
{
char ans = 0;
do
{
system("cls");
cout << "Name: "; cin >> person[count].name;
system("cls");
cout << "Age: "; cin >> person[count].age;
system("cls");
cout << "Gender(M/F/H): "; cin >> person[count].gender;
system("cls");
cout << "Comments: "; cin >> person[count].comments;
count++;
system("cls");
cout << "Add another person?(y/n): "; cin >> ans;
}
while(ans == 'y');
system("cls");
}
int main()
{
App program;
program.Run();
}
I wanted to pass an object - which is also a vector - through a function using pointers.
I believe the issue arises on line 75 (transaction(&user, userID);) where I attempt to pass the object "user" through to the function "transaction".
I don't believe the classes are relevant so I left them out. Thank you so much in advance. Here is the source.cpp code:
void transaction(vector<Customer *> &user, int userID);
void newAccount(vector<Customer*> & user, int userID);
void intr(vector<Customer*> & user, int userID, int account, int interest);
void loans(vector<Customer*> & user, int userID, int account, int loan);
int main()
{
vector<Customer> user(3);
user[0].setname("Josh");
user[0].setID(1);
user[0].bank[0].setbalance(100);
user[0].bank[1].setbalance(101);
user[0].bank[0].setoverdraft(200);
user[0].bank[1].setoverdraft(201);
user[0].accounts = 1;
user[0].setpin(1202);
user[1].setname("John");
user[1].setID(2);
user[1].bank[0].setbalance(102);
user[1].bank[0].setoverdraft(202);
user[1].accounts = 0;
user[1].setpin(1203);
user[2].setname("Jack");
user[2].setID(3);
user[2].bank[0].setbalance(103);
user[2].bank[0].setoverdraft(203);
user[2].accounts = 0;
user[2].setpin(1204);
int input;
int userID;
int pin;
int account;
bool menu = true;
//Menu
while (menu)
{
cout << " - Enter '1' to display all customer names and ID's." << endl;
cout << " - Enter '2' for further transactions." << endl;
cout << " - Enter '3' to make a quick withdrawal of " << char(156) << "10 from an account." << endl;
cout << " - Enter '4' to exit." << endl;
cin >> input;
// List
if (input == 1)
{
for (int i = 0; i < user.size(); i++)
{
cout << "[Name: " << user[i].getname() << "\t" << "ID: " << user[i].getID() << "]" << endl;
}
cout << endl;
}
// Transactions
else if (input == 2)
{
cout << "Enter Customer ID: ";
cin >> userID;
cout << "Enter pin: ";
cin >> pin;
if (pin == user[userID].getpin())
{
transaction(&user, userID);
}
else { cout << "Pin invalid." << endl; }
}
// Quick withdrawal
else if (input == 3)
{
cout << "Enter Customer ID: ";
cin >> userID;
cout << "Enter pin: ";
cin >> pin;
cout << "Enter the account you wish to make a withdrawal from: ";
cin >> account;
if (pin == user[userID].getpin())
{
if (account <= user[userID].accounts)
{
if (user[userID].bank[account].getbalance() - 10 <= -user[userID].bank[account].getoverdraft())
{
user[userID].bank[account].withdraw(10);
}
else { cout << "Insignificunt funds. Overdraft limit (" << char(156) << user[userID].bank[account].getoverdraft() << ")" << endl; }
}
else { cout << "That account does not exist." << endl; }
}
else { cout << "Pin invalid." << endl; }
}
// Exit
else if (input == 4)
{
menu = false;
}
}
return 0;
}
void transaction(vector<Customer *> &user, int userID){...}
ERROR DESCRIPTION: initial value of reference to non-const must be an lvalue.
you are passing wrong arguments to the transaction() first parameter takes reference to vector of customer pointer
std::vector<Customer*> &user
but you are passing an address of vector of customer
vector<Customer> user(3);
transaction(&user, userID);
you should change vector<Customer> to vector<Customer*> user(3).
or
change void transaction(vector<Customer *> &user, int userID);
to void transaction(vector<Customer> &user, int userID);
the same goes for other functions if you are doing the same thing.
about the error, are you sure this is the problem?
There are two main problems with my program that I am currently having. The first is I am unable to add more than one account to my program while it is running (I need to close it and re-open before I can add another). The second issue is when I don't add any accounts to my program addresses get saved to the program, this is what the file looks like when I don't add any accounts to the program.
123#John Smith#0#0###-1.07374e+008#-1.07374e+008#
The first part of the file is correct, but the addresses are coming from somewhere else in memory. This is what my code looks like.
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>
#include <sstream>
using namespace std;
struct account
{
string acctNum;
string name;
float cBal;
float sBal;
};
int menu();
char subMenu();
int loadCustomers(account[]);
void saveCusomers(account[], int);
int newCustomer(account[], int);
int deleteCustomer(account[], int);
int findCustomer(account[], int);
void deposit(account[], int);
void withdrawl(account[], int);
void balance(account[], int);
void bankBalance(account[], int);
int main()
{
account acc[20];
int selection;
int numAcc = 0;
int search;
numAcc = loadCustomers(acc);
do
{
selection = menu();
if(selection == 1)
{
newCustomer(acc, numAcc);
}
else if(selection == 2)
{
deleteCustomer(acc, numAcc);
}
else if(selection == 3)
{
search = findCustomer(acc, numAcc);
if (search == -1)
{
cout << "That account doesn't exist." << endl;
system("pause");
system("cls");
}
else
{
cout << right << setw(3) << acc[search].acctNum << "" << left << setw(15) << acc[search].name << acc[search].cBal << acc[search].sBal << endl;
system("pause");
system("cls");
}
}
else if(selection == 4)
{
deposit(acc, numAcc);
}
else if(selection == 5)
{
withdrawl(acc, numAcc);
}
else if(selection == 6)
{
balance(acc, numAcc);
}
else if(selection == 7)
{
bankBalance(acc, numAcc);
}
else if(selection == 8)
{
break;
}
} while (selection != 8);
saveCusomers(acc, numAcc);
return 0;
}
int menu()
{
int select;
cout << "Main Menu" << endl;
cout << "=============" << endl;
cout << "1. New Account" << endl;
cout << "2. Delete Account" << endl;
cout << "3. Find Customer" << endl;
cout << "4. Deposit" << endl;
cout << "5. Withdrawl" << endl;
cout << "6. Balance" << endl;
cout << "7. Bank Balance" << endl;
cout << "8. Exit" << endl;
cout << "=============" << endl;
cout << "Enter choice: ";
cin >> select;
while (select < 1 || select > 8)
{
cout << "Invalid input, select a number between 1 and 8: ";
cin >> select;
}
system("cls");
return select;
}
char subMenu()
{
char choice;
cout << "Which account? <C>hecking or <S>aving: ";
cin >> choice;
while(choice != 'C' && choice != 'c' && choice != 'S' && choice != 's')
{
cout << "Invalid choice, choose either checking or saving: ";
cin >> choice;
}
return choice;
}
int loadCustomers(account acc[])
{
ifstream inFile;
int numCustomers = 0, i = 0;
string ctemp, stemp;
inFile.open("customer.dat");
if (!inFile)
{
cout << "No customer file found." << endl;
}
else
{
cout << "Customer file found..." << endl << endl;
while (getline(inFile, acc[i].acctNum, '#'))
{
getline(inFile, acc[i].name, '#');
getline(inFile, ctemp, '#');
getline(inFile, stemp, '#');
istringstream(ctemp) >> acc[i].cBal;
istringstream(stemp) >> acc[i].sBal;
i++;
numCustomers++;
}
cout << "Number of customers found in file: " << numCustomers << endl;
}
system("pause");
system("cls");
inFile.close();
return numCustomers;
}
void saveCusomers(account acc[], int numCustomers)
{
ofstream outFile;
outFile.open("customer.dat");
for (int i = 0; i < numCustomers; i++)
{
outFile << acc[i].acctNum;
outFile << '#';
outFile << acc[i].name;
outFile << '#';
outFile << acc[i].cBal;
outFile << '#';
outFile << acc[i].sBal;
outFile << '#';
}
outFile << acc[numCustomers].acctNum;
outFile << '#';
outFile << acc[numCustomers].name;
outFile << '#';
outFile << acc[numCustomers].cBal;
outFile << '#';
outFile << acc[numCustomers].sBal;
outFile << '#';
cout << numCustomers + 1 << " accounts saved into the file." << endl;
outFile.close();
}
int newCustomer(account acc[], int numCustomers)
{
cout << "New Customer" << endl;
cout << "============" << endl;
cout << "Enter account number: ";
cin >> acc[numCustomers].acctNum;
cout << "Enter name: ";
cin.ignore();
getline(cin, acc[numCustomers].name);
acc[numCustomers].cBal = 0;
acc[numCustomers].sBal = 0;
numCustomers++;
return numCustomers;
}
int deleteCustomer(account[], int)
{
return 0;
}
int findCustomer(account acc[], int numCustomers)
{
string target;
cout << "Enter the account number you are looking for: ";
cin >> target;
for (int i = 0; i < numCustomers; i++)
{
if (acc[i].acctNum == target)
{
return i;
}
}
return -1;
}
How can I change this to make it so I can add more than one account when the program is running, and how can I make it so the program won't save an address to my file when nothing is added? I would also like to know why those addresses are being saved like that.
In main() you loadCustomers() in acc[] and you keep a record of the number of customers in local variable numAcc. At the end of main() you saveCustomers() the numAcc in acc[].
1. Your saving function is wrong:
in your loop for (int i = 0; i < numCustomers; i++) { ...}, you first write each customer from 0 to numAcc-1. This is correct.
But afterwards you write again an additional account, with the offset of numAcc. So you're writng one more account than you have. And the values of this account are not initialized, which explains the weird numbers you see.
You do this even if no account was added. And you know that you are doing it, because you've written cout << numCustomers + 1 << " accounts saved into the file."
Correction: just save the accounts you have, in the loop.
2.Your adding function is correct but you don't use it as you've planned:
When you add a customer with newCustomer() your function increments its local variable so that it knows that there is one more customer. Your function correctly returns this new number.
Unfortunately, in main() you do nothing with this returned value, so that numAcc remains unchanged.
Correction: Correct the following statement in main():
if (selection == 1)
{
numAcc = newCustomer(acc, numAcc); // update the number of accounts
}
3. Miscellaneous remarks:
You don't check in newCustomers() if your acc[] array is already full. If you add a 21st account, it'll be a segfault !
The same applies to load. You cannot be sure that nobody added a line to the file with a text editor. So there is as well a risk of reading more lines that there is space in your arry.
Nothing happens in deleteCustomer() I suppose you haven't written it yet. Think that this function could change the number of accounts, exactly as newCustomer().
As most banks have more than twenty customers, I assume that it's an exercise for school. I don't know if you're allowed to do so, but I'd highly recommend to replace arrays with vectors.