Difficulties with saving a text file using ofstream - c++

Right now my problem seems to be focused on the saveFile function.
I will post the entire program here, so dont be ired when see a whole bunch of code... just look at the saveFile function at the bottom... I am posting all the code JUST IN CASE it will help you help me solve my problem.
Now for defining the apparent problem to you all: I can edit the file throughout the life of the console app with the updateSale function as I run it, but when I use the saveFile function and put in 'y' to save, the differences that are visible after using the updateSales function DO NOT get saved to the actual sales file called "salespeople.txt" and I do not understand why.
this is what the salespeople.txt looks like:
Schrute 25000
Halpert 20000
Vance 19000
Hudson 17995.5
Bernard 14501.5
now here is the program:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//variables--------------------------------------------------------
int lineCount = 0;
//prototypes-------------------------------------------------------
int getIndexLargest(string[], double[]);
void displaySalesPeople(string[], double[]);
bool readSalesFile(string[], double[]);
void updateSales(string[], double[]);
int saveFile(string, string[], double[], int);
int main()
{
string fileName;
int arrayLength;
ifstream readSales;
string salesPersonName[5];
double saleAmount[5];
bool flag = false;
int options;
do
{
cout << "1) Open sales person file. "<< endl;
cout << "2) Display sales person information. "<< endl;
cout << "3) Update sales. " << endl;
cout << "4) Get best sales person. " << endl;
cout << "5) Exit. " << endl;
cout << "Please enter a number 1-5 to select an option." <<endl;
cin >> options;
if(options == 1)
{
flag = readSalesFile(salesPersonName, saleAmount);
}
else if(options == 2)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
displaySalesPeople(salesPersonName, saleAmount);
}
else if(options == 3)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
updateSales(salesPersonName, saleAmount);
}
else if(options == 4)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
getIndexLargest(salesPersonName, saleAmount);
}
else if(options == 5)
{
char choice;
cout << "Enter character y to save... anything else will exit without saving: " << endl;
cin >> choice;
if(choice == 'y')
{
saveFile(fileName, salesPersonName, saleAmount, arrayLength);
cout << "File saved. " << endl;
}
else
{
cout << "closing program" << endl;
}
}
}
while(options != 5);
return 0;
}
//functions---------------------------------
bool readSalesFile(string salesPersonName[], double saleAmount[])
{
bool flag = false;
ifstream readSales;
string fileName;
cout << "Please enter the path to your sales people file: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
while(readSales.fail())
{
cout << "Failed. Please enter the path to your sales file again: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
}
if(readSales.good())
{
flag = true;
cout << lineCount;
string name = " ";
double amount =0.00;
int i = 0;
while(!readSales.eof())
{
readSales >> name;
readSales >> amount;
salesPersonName[i] = name;
saleAmount[i] = amount;
i++;
}
for(i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
readSales.close();
}
readSales.close();
return flag;
}
void displaySalesPeople(string salesPersonName[], double saleAmount[])
{
for(int i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
}
void updateSales(string salesPersonName[], double saleAmount[])
{
bool flag = false;
string findName;
double moneyAmount;
cout << "Enter name of sales person you want to modify: " << endl;
cin >> findName;
for(int i = 0; i < 5; i++)
{
if(findName == salesPersonName[i])
{
cout << "Enter the sale amount you would like to modify: " << endl;
cin >> moneyAmount;
saleAmount[i] += moneyAmount;
cout << saleAmount[i] << endl;
flag = true;
}
}
if(flag == false)
{
cout << " name not found" << endl;
}
}
int getIndexLargest(string salesPersonName[], double saleAmount[])
{
ifstream readSales;
while(!readSales.eof())
{
double largestSale = 0.00;
string largestSalesPerson;
int i = 0;
lineCount++;
readSales >> salesPersonName[i];
readSales >> saleAmount[i];
if(saleAmount[i] > largestSale)
{
largestSale = saleAmount[i];
largestSalesPerson = salesPersonName[i];
}
cout << "Best sales person : "<< largestSalesPerson << " $" <<setprecision(2)<<fixed<< largestSale << endl;
}
}
int saveFile(string fileName, string salesPersonName[], double saleAmount[], int arrayLength)
{
ofstream saveFile(fileName.c_str());
saveFile.open(fileName.c_str());
for(int i = 0; i < 5; i++)
{
saveFile << salesPersonName[i] << " " << saleAmount[i] << endl;
}
saveFile.close();
return 0;
}

You are trying t open your file twice:
ofstream saveFile(fileName.c_str()); // this opens the file
saveFile.open(fileName.c_str()); // so does this
That will put the file in an error state so no writing will happen.
Just do this:
ofstream saveFile(fileName.c_str()); // this opens the file
And that should work.
Or else you can do this:
ofstream saveFile; // this does not open the file
saveFile.open(fileName.c_str()); // but this does
And that should work too.

Related

C++ Incrementing Object Counter and Multiple Object Creation Issue

I was wondering if someone could help me on figuring out how to create multiple structs and also counting the number of structs created.
My Code follows three blocks, header file, Television file and then the main file.
Television.h
#include <iostream>
#include <string>
using namespace std;
class Televison {
string Manufacturer;
string Type; //Plasma, LCD
string Model; //Smart, regular
string Connection; //HDMI, VGA
string Power;
double Price;
int Serial_Number;
int Screen_size;
int Resolution; //larger one, so 1920 and etc.
int Channel; //any number
int Volume; //0 - 100
public:
//constructor
Televison(string Manufacturer, string Type, string Model, string Connection, string Power, double Price, int Serial_number, int Screen_size, int Resolution, int Channel, int Volume);
//Destructor
~Televison();
//Accessor Methods
string get_Manufacturer();
string get_Type();
string get_Model();
string get_Connection();
string get_Power();
double get_Price();
int get_Serial_Number();
int get_Screen_size();
int get_Resolution();
int get_Channel();
int get_Volume();
//mutator methods
string input_Manufacturer(string Manufacturer);
string input_Type(string Type);
string input_Model(string Model);
string input_Connection(string Connection);
string input_Power(string Power);
double input_Price(double Price);
int input_Serial_Number(int Serial_Number);
int input_Screen_size(int Screen_size);
int input_Resolution(int Resolution);
int input_Channel(int Channel);
int input_Volume(int Volume);
string change_Power(string Power);
int change_Channel(int Channel);
int change_Volume(int Volume);
};
static int num_tel = 1; //number of Televisons that will be incremented
Television.cpp
#include <iostream>
#include <string>
#include "Televison.h"
using namespace std;
//constructor
Televison::Televison(string Manufacturer, string Type, string Model, string Connection, string Power, double Price, int Serial_number, int Screen_size, int Resolution, int Channel, int Volume) {
this->Manufacturer = Manufacturer;
this->Type = Type;
this->Model = Model;
this->Connection = Connection;
this->Power = Power;
this->Price = Price;
this->Serial_Number = Serial_Number;
this->Screen_size = Screen_size;
this->Resolution = Resolution;
this->Channel = Channel;
this->Volume = Volume;
num_tel++;
// initiliazes the variables to default values
Manufacturer = "Sony";
Type = "Smart";
Model = "Plasma";
Connection = "HDMI";
Power = "ON";
Serial_Number = 1234;
Price = 199.00;
Screen_size = 50;
Resolution = 1440;
Channel = 100;
Volume = 100;
}
//Destructor
Televison::~Televison() {
cout << "The " << Manufacturer << " " << Model << " has finished shutting down." << endl;
num_tel--;
cout << "The inventory of television is now: " << num_tel << endl;
}
//Get Methods
string Televison::get_Manufacturer() {
return Manufacturer;
}
string Televison::get_Model() {
return Model;
}
string Televison::get_Type() {
return Type;
}
int Televison::get_Serial_Number() {
return Serial_Number;
}
string Televison::get_Connection() {
return Connection;
}
string Televison::get_Power() {
return Power;
}
double Televison::get_Price() {
return Price;
}
int Televison::get_Screen_size() {
return Screen_size;
}
int Televison::get_Resolution() {
return Resolution;
}
int Televison::get_Channel() {
return Channel;
}
int Televison::get_Volume() {
return Volume;
}
//mutator methods
int Televison::change_Channel(int Channel1) {
if (Channel > 0)
{
Channel = Channel1;
return Channel;
}
else
{
cout << "Invalid Channel, please enter another number" << endl;
return Channel;
}
}
int Televison::change_Volume(int Volume1) {
if (Volume1 > 0)
{
Volume = Volume1;
return Volume;
}
else
{
cout << "Invalid volume, please enter another number" << endl;
return Volume;
}
}
string Televison::change_Power(string Power1) {
if (Power1 =="Y")
{
Power = Power1;
return Power;
}
else
{
return Power;
}
}
string Televison::input_Connection(string Connection1) {
Connection = Connection1;
return Connection;
}
string Televison::input_Type(string M) {
Type = M;
return Type;
}
string Televison::input_Manufacturer(string M) {
Manufacturer = M;
return Manufacturer;
}
/*
string Televison::Manufacturer_code(string M,string N) {
string J = M.substr(0,4);
string Manufacturer_code = J + N;
return Manufacturer_code;
}
*/
string Televison::input_Model(string M) {
Model = M;
return Model;
}
string Televison::input_Power(string M) {
Power = M;
return Power;
}
double Televison::input_Price(double M) {
Price = M;
return Price;
}
int Televison::input_Serial_Number(int M) {
Serial_Number = M;
return Serial_Number;
}
int Televison::input_Screen_size(int M) {
Screen_size = M;
return Screen_size;
}
int Televison::input_Resolution(int M) {
Resolution = M;
return Resolution;
}
int Televison::input_Channel(int M) {
Channel = M;
return Channel;
}
int Televison::input_Volume(int M) {
Volume = M;
return Volume;
}
Source.cpp
#include <iostream>
#include <string>
#include "Televison.h"
using namespace std;
void displayStatus(Televison& Televison) {
cout << "Inventory of Televisons: " << num_tel << endl;
cout << "The Televison serial number: " << Televison.get_Serial_Number() << " " << Televison.get_Manufacturer() << " " << Televison.get_Model() << " " << Televison.get_Type() << " with " << Televison.get_Connection() << " ";
cout << "\n with " << Televison.get_Power() << " " << Televison.get_Price() << " with " << Televison.get_Screen_size() << " screen size " << Televison.get_Resolution() << "p " << "with " << Televison.get_Channel() << " channel " << Televison.get_Volume() << " Volume " << endl;
}
int main() {
{
Televison Televison_1("Sony", "Smart", "Plasma", "HDMI", "ON", 199.00, 1234, 50, 1440, 100, 100); //default Televison
cout << "This is the Televison program for personal Televison: " << endl;
bool repeat = true;
do {
cout << "Please enter the Manufacturer for the Televison: " << endl;
string Manufacturer;
getline(cin, Manufacturer);
int M1 = Manufacturer.length();
if (M1 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Manufacturer(Manufacturer);
} while (!repeat);
repeat = true;
do {
cout << "Please enter the Type of the Televison: " << endl;
string Type;
getline(cin, Type);
int M3 = Type.length();
if (M3 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Type(Type);
} while (!repeat);
repeat = true;
do {
cout << "Please enter the Model for the Televison: " << endl;
string Model;
getline(cin, Model);
int M2 = Model.length();
if (M2 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Model(Model);
} while (!repeat);
cout << "Please enter the Connection for the Televison: " << endl;
string Connection;
cin >> Connection;
Televison_1.input_Connection(Connection);
cout << "Enter the Serial Number: " << endl;
int inp4;
cin >> inp4;
Televison_1.input_Serial_Number(inp4);
cout << "Enter the Screen size: " << endl;
cin >> inp4;
Televison_1.input_Screen_size(inp4);
cout << "Enter the Resolution: " << endl;
cin >> inp4;
Televison_1.input_Resolution(inp4);
int a = 0;
while (a < 1)
{
cout << "Please enter the Price for the Televison: " << endl;
double Price;
cin >> Price;
if (Price > 0) //address speed must be greater than 0
{
Televison_1.input_Price(Price);
a++;
}
else
cout << "Invalid, enter again." << endl;
}
displayStatus(Televison_1);
int b = 0;
while (b < 1)
{
cout << "Would you like to Power your Televison? (Y/N)" << endl;
char input1;
cin >> input1;
if (input1 == 'Y' || input1 == 'y')
{
Televison_1.change_Power("ON");
b++;
}
else if (input1 == 'N' || input1 == 'n')
{
Televison_1.change_Power("OFF");
b++;
}
else
cout << "Invalid, enter again." << endl;
}
displayStatus(Televison_1);
int n = 0;
int n1 = 0;
while (n < 1)
{
cout << "Would you like to change any of the following attributes of your Televison? (Y/N)";
string input2, input3;
int input4;
double input5;
cin >> input2;
if (input2 == "Y" || input2 == "y")
{
while (n1 < 1) {
cout << "Which Televison attribute would you like to change? (Enter the respective number): " << endl;
cout << "1: Manufacturer" << endl;
cout << "2: Type" << endl;
cout << "3: Model" << endl;
cout << "4: Serial Number" << endl;
cout << "5: Connection" << endl;
cout << "6: Power" << endl;
cout << "7: Channel" << endl;
cout << "8: Screen size" << endl;
cout << "9: Resolution" << endl;
cout << "10: Volume" << endl;
cout << "11: Price" << endl;
int choice;
cin >> choice;
bool repeat1 = true;
bool repeat2 = true;
bool repeat3 = true;
switch (choice)
{
case 1:
cout << "Enter the Manufacturer: " << endl;
cin >> input3;
Televison_1.input_Manufacturer(input3);
break;
case 2:
cout << "Enter the Type: " << endl;
cin >> input3;
Televison_1.input_Type(input3);
break;
case 3:
cout << "Enter the Model: " << endl;
cin >> input3;
Televison_1.input_Model(input3);
break;
case 4:
cout << "Enter the Serial Number: " << endl;
cin >> input4;
Televison_1.input_Serial_Number(input4);
break;
case 5:
cout << "Enter the Connection: " << endl;
cin >> input3;
Televison_1.input_Connection(input3);
break;
case 6:
cout << "Enter the power: " << endl;
cin >> input3;
Televison_1.input_Power(input3);
break;
case 7:
cout << "Enter the Channel " << endl;
cin >> input4;
Televison_1.input_Channel(input4);
break;
case 8:
cout << "Enter the Screen size: " << endl;
cin >> input4;
Televison_1.input_Screen_size(input4);
break;
case 9:
do {
cout << "Enter the Resolution: " << endl;
cin >> input4;
if (input4 < 0)
{
cout << "Please enter a speed above 0" << endl;
repeat1 = false;
}
else
{
Televison_1.input_Resolution(input4);
repeat1 = true;
}
} while (!repeat1);
break;
case 10:
do {
cout << "Enter the Volume: " << endl;
cin >> input4;
if (input4 >= 0) {
cout << "Please enter a valid volume" << endl;
repeat2 = false;
}
else
{
repeat2 = true;
Televison_1.change_Volume(input4);
}
} while (!repeat2);
break;
case 11:
do {
cout << "Enter the Price: " << endl;
cin >> input5;
if (input5 > 0)
{
Televison_1.input_Price(input5);
repeat3 = true;
}
else
{
cout << "Please enter a valid price" << endl;
repeat3 = false;
}
} while (!repeat3);
break;
}
displayStatus(Televison_1);
cout << "Would you like to change another attribute? (Y/N)" << endl;
cin >> input3;
if (input3 == "Y" || input3 == "y")
{
}
else
n1++;
}
n++;
}
else if (input2 == "N" || input2 == "n")
{
cout << "The Televison will begin to shut down." << endl;
n++;
displayStatus(Televison_1);
}
else
cout << "Invalid, enter again." << endl;
}
}
// object goes out of scope - the destructor which shuts down the Televison
system("pause");
return 0;
}
Basically, my code only allows me to create one object and modify it. However, I would like to add the ability to create multiple objects and have a counter for it. I tried adding a counter, but it seems that doesn't work very well... I don't need someone to solve it, but if someone could point me to the right direction, that would be great.

C++ MDC Final - Sort Names in Records Alphabetically While in Array Struct of Type Char

I was able to write a program to pass my c++ class in college except for one feature. I was unable to create a function that sorted the names inside an array of structs with name of type char alphabetically. Please advise on how to tackle this problem.
I would need a function that sorts the accountRecords array alphabetically.
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
//Structure Initilizations
const int NAME_SIZE = 25, ADDR_SIZE = 100, CITY_SIZE = 51, STATE_SIZE = 4, DATE_SIZE = 16, CUSTOMER_ID = 10, TRANSACTION_TYPE = 16;
struct MasterRecord
{
int customerID;
char name[NAME_SIZE]; // SORT THIS FIELD ALPHABETICALLY
char address[ADDR_SIZE];
char city[ADDR_SIZE];
char state[STATE_SIZE];
char zip[STATE_SIZE];
float accountBalance;
char lastTransactionDate[15];
};
struct TransactionRecord
{
int customerID;
char transactionType;
float amount;
char transactionDate[15];
};
//File Array Initializations
vector<MasterRecord> masterRecordList(101);
vector<TransactionRecord> transRecordList(101);
//Array List Record Position
int masterRecordArrayPosition = 0;
int transactionRecordArrayPosition = 0;
//User Menu Answer Variable Initialization
int userAnswer = 0;
string recordNotFoundAnswer = "";
//Print Function Prototypes
void showMenu();
void showMasterRecord(int);
void showTransactionRecord(int);
//Main Menu Function Prototypes
void newCustomerRecord(int);
void editCustomerRecord(int);
void deleteCustomerRecord(int);
int randomComputerID();
int searchMasterRecord(int);
void saveAccountRecords();
void saveTransRecords();
void newTransactionRecord(int);
//Placeholders Variables
int customerIDsearch = 0;
int customerIDSearchArrayPosition = 0;
int userNameCharactererror = 0;
//Function Loop Counters
int accountWriteCounter = 0;
int transWriteCounter = 0;
int showRecordCounter = 0;
int showTransCounter = 0;
//System time Declaration and Conversion for [lastTransactionDate]
time_t now = time(0);
tm *ltm = localtime(&now);
string currentYearInString = to_string(1900 + ltm->tm_year);
string currentMonthInString = to_string(1 + ltm->tm_mon);
string currentDayInString = to_string(ltm->tm_mday);
string currentDateInString = currentMonthInString + "/" + currentDayInString + "/" + currentYearInString;
char dateInChar[15];
//Main Program
int main()
{
//Final conversion of time in string to char for storage
strncpy_s(dateInChar, currentDateInString.c_str(), 15);
//Open MasterRecord file and read records to arrays
fstream masterRecord("masterRecord.dat", ios::in | ios::binary);
int listCounter = 0;
if (!masterRecord) {
cout << "Unable to open the user records file, creating file database....Done!" << endl;
masterRecord.open("masterRecord.dat", ios::out | ios::binary);
}
else {
while (!masterRecord.eof()) {
masterRecord.read(reinterpret_cast<char *>(&masterRecordList[listCounter]), sizeof(masterRecordList[0]));
if (masterRecordList[listCounter].customerID != 0) {
listCounter++;
}
masterRecordArrayPosition = listCounter;
}
masterRecord.close();
}
//Open Transaction Record and read to arrays
fstream transactionRecord("transactionRecord.dat", ios::in | ios::binary);
int listCounter2 = 0;
if (!transactionRecord) {
cout << "Unable to open the transaction file, creating file database....Done!" << endl << endl;
transactionRecord.open("transactionRecord.dat", ios::out | ios::binary);
}
else {
while (!transactionRecord.eof()) {
transactionRecord.read(reinterpret_cast<char *>(&transRecordList[listCounter2]), sizeof(transRecordList[0]));
if (transRecordList[listCounter2].customerID != 0) {
listCounter2++;
}
transactionRecordArrayPosition = listCounter2;
}
transactionRecord.close();
}
//Time Declaration Used to Generate Random IDs
srand((unsigned)time(0));
//Main user Program Loop
while (userAnswer != 6) {
showMenu();
cin >> userAnswer; cout << endl;
//Menu Input Data Validation
if (cin.fail()) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
cin.clear();
cin.ignore();
}
else {
if (userAnswer < 1 || userAnswer > 7) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
userAnswer = 0;
}
}
//Menu Selection Switch Case
switch (userAnswer) {
case 1:
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
break;
case 2:
newTransactionRecord(transactionRecordArrayPosition);
break;
case 3:
cout << "Please enter the Customer ID you would like to Delete" << endl << endl; //[Delete Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
deleteCustomerRecord(customerIDSearchArrayPosition);
}
break;
case 4:
cout << "Please enter the Customer ID you would like to edit." << endl << endl; //[Search/Edit Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
editCustomerRecord(customerIDSearchArrayPosition);
}
else {
cout << "Record was not found, would you like to add a new record? Y = Yes, N = No" << endl << endl;
cin >> recordNotFoundAnswer;
if (recordNotFoundAnswer == "Y" | recordNotFoundAnswer == "y") {
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
}
else if (recordNotFoundAnswer == "N" | recordNotFoundAnswer == "n") {
userAnswer = 0;
}
}
break;
case 5:
cout << setw(212) << "Please find all customer records in the database" << endl << endl; //[Show all Records] Function goes here
cout << setw(40) << "Name:" << setw(10) << "ID:" << setw(23) << "Street Address:" <<setw(10) << "ZIP:" << setw(16) << "L.Trans Date:" << setw(11) << "Balance: " << endl;
while (showRecordCounter < 100) {
if (masterRecordList[showRecordCounter].customerID != 0) {
showMasterRecord(showRecordCounter);
}
showRecordCounter = showRecordCounter + 1;
} showRecordCounter = 0;
userAnswer = 0;
cout << endl;
break;
case 6:
cout << "Saving changes to database...Done!" << endl;
saveAccountRecords();
saveTransRecords();
cout << "Done!" << endl;
break;
case 7:
cout << "Showing all transaction Records:" << endl << endl;
while (showTransCounter < 100) {
if (transRecordList[showTransCounter].customerID != 0) {
showTransactionRecord(showTransCounter);
}
showTransCounter = showTransCounter + 1;
} showTransCounter = 0;
userAnswer = 0;
break;
}
}
return 0;
}
//Databas Management Functions
void saveAccountRecords() {
fstream masterRecord("masterRecord.dat", ios::out | ios::binary);
while (accountWriteCounter < 100) {
masterRecord.write(reinterpret_cast<char *>(&masterRecordList[accountWriteCounter]), sizeof(masterRecordList[0]));
accountWriteCounter++;
}
masterRecord.close();
}
void saveTransRecords() {
fstream transRecord("transactionRecord.dat", ios::out | ios::binary);
while (transWriteCounter < 100) {
transRecord.write(reinterpret_cast<char *>(&transRecordList[transWriteCounter]), sizeof(transRecordList[0]));
transWriteCounter++;
}
transRecord.close();
}
//Random Function
int randomComputerID() {
int randomNumber;
randomNumber = (rand() % 1000) + 10000;
return randomNumber;
}
//Program Print Functions
void showMenu() {
cout << "Welcome to your C++ company terminal! Please enter one of the options below to continue." << endl << endl;
cout << "1. New Customer Record" << endl;
cout << "2. New Transaction Record" << endl;
cout << "3. Delete Customer Record" << endl;
cout << "4. Edit Customer Record" << endl;
cout << "5. Show all Account Records in Database" << endl;
cout << "6. Exit and Save Changes to Database" << endl << endl;
cout << "Please enter the number for the correspondent action you would like to perform:" << endl;
}
void showMasterRecord(int arrayNum) {
cout << setw(40)
<< masterRecordList[arrayNum].name << setw(10) << masterRecordList[arrayNum].customerID << setw(23)
<< masterRecordList[arrayNum].address << setw(10)
<< masterRecordList[arrayNum].zip << setw(16)
<< masterRecordList[arrayNum].lastTransactionDate << setw(6) <<"$"
<< masterRecordList[arrayNum].accountBalance; cout << endl;
}
void showTransactionRecord(int arrayNum) {
cout << "Customer ID: " << transRecordList[arrayNum].customerID << endl;
cout << "Amount: $" << transRecordList[arrayNum].amount << endl;
cout << "Transaction Type: " << transRecordList[arrayNum].transactionType << endl;
cout << "Transaction Date: " << transRecordList[arrayNum].transactionDate << endl << endl;
}
//Main Menu Functions [Please insert your functions here and prototype them above].
void newCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
masterRecordList[arrayNum].customerID = randomComputerID();
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
do
{
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 25);
if (cin.fail()) {
cout << endl << "Please enter only characters up 25 chracters for your name." << endl;
userNameCharactererror = 1;
cin.clear();
cin.ignore(80, '\n');
}
else {
userNameCharactererror = 0;
}
} while (userNameCharactererror == 1);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Opening Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
masterRecordArrayPosition = masterRecordArrayPosition + 1;
}
void editCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 51);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Edit Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
}
void deleteCustomerRecord(int arrayNum) {
if (masterRecordList[arrayNum].accountBalance == 0)
{
masterRecordList[arrayNum].customerID = 0;
cout << "Record has been deleted" << endl << endl;
}
else {
cout << "Unable to delete record, customer accounts holds a positive balance" << endl << endl;
}
}
int searchMasterRecord(int customerID) //Search by customer name and returns array position
{
int arrayPosition = 0;
int arrayCounter = 0;
int customerIdPlaceholder = 0;
while (arrayCounter < 100) {
customerIdPlaceholder = masterRecordList[arrayCounter].customerID;
if (customerIdPlaceholder == customerID) {
cout << "Record has been found!" << endl << endl;
arrayPosition = arrayCounter;
arrayCounter = 100;
}
else {
arrayPosition = 9999;
}
arrayCounter = arrayCounter + 1;
}
return arrayPosition;
};
void newTransactionRecord(int arrayNum) {
// Request customer ID and transaction type from the user
cout << "Customer ID: ";
cin >> transRecordList[arrayNum].customerID;
cin.ignore();
cout << "Date: ";
strncpy_s(transRecordList[arrayNum].transactionDate, dateInChar, 15);
cout << transRecordList[arrayNum].transactionDate << endl;
cout << "Transaction Type [D = Deposit] [W = Withdrawal]: ";
cin >> transRecordList[arrayNum].transactionType;
cout << "Amount: $";
cin >> transRecordList[arrayNum].amount;
//Search for customer account, update balance, and assign last transaction date
customerIDSearchArrayPosition = searchMasterRecord(transRecordList[arrayNum].customerID);
if (customerIDSearchArrayPosition != 9999) {
if (transRecordList[arrayNum].transactionType == 'D') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance + transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Deposit Successful! " << endl << endl;
}
else if (transRecordList[arrayNum].transactionType == 'W') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance - transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Withdrawl Successful" << endl << endl;
}
}
else {
cout << "Customer account record was not found, transaction was not saved." << endl << endl;
}
transactionRecordArrayPosition = transactionRecordArrayPosition + 1;
}
Something along these lines:
std::sort(masterRecordList.begin(),
masterRecordList.begin() + masterRecordArrayPosition,
[](const MasterRecord& l, const MasterRecord& r) {
return strcmp(l.name, r.name) < 0;
});

How to put a random number into an array then a text file

So what I am trying to do is put a random number generator from one through ten into an array that has 50 elements and then put that into a text file. My problem is that the code I have written for the code and generator has an error and I can't wrap my head around how to get it into a text file.
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include<fstream>
using namespace std;
void menu();
string createFile();
void displayNumTotalAverage(string);
void displaySortedNums();
void SearchNum();
void displayLargestNum();
void appendRandomNum(string);
void exit();
void CreateFile();
void printFunc(int[]);
void fillFunc(int[]);
int main()
{
menu();
string FileName;
//createFile();
//makeRandomNum();
system("pause");
return 0;
}
void menu()
{
int choice;
string FileName;
do
{
//program output
cout << "** MENU **" << endl << endl;
cout << "Curret Data File: " << endl << endl;
cout << "(1) Select / create data file (.txt file extention will be added automaticly)" << endl;
cout << "(2) Display all numbers, total and average" << endl;
cout << "(3) Display all numbers sorted" << endl;
cout << "(4) search for a number and display how many times it occurs" << endl;
cout << "(5) display the largest number" << endl;
cout << "(6) Append a random number(s)" << endl;
cout << "(7) Exit the program" << endl << endl;
//user input
cout << "Menu Choice: ";
cin >> choice;
while (choice > 7 || choice < 1)
{
cout << "Menu Choice: ";
cin >> choice;
}
switch (choice)
{
case 1:
cout << "Choice 1";
createFile();
break;
case 2:
cout << "Choice 2";
displayNumTotalAverage(FileName.c_str());
break;
case 3:
cout << "Choice 3";
break;
case 4:
cout << "Choice 4";
break;
case 5:
cout << "Choice 5";
break;
case 6:
cout << "Choice 6";
appendRandomNum(FileName.c_str());
break;
}
} while (choice != 7);
}
string createFile()<----------------------------------------------------(this)
{
cout << "Create File - Option 1" << endl;
string FileName;
ifstream inFile;
cout << "Name of data file: ";
cin >> FileName;
FileName = "C:\\Users\Wizard\Libraries\Documents\Final Project" + FileName;
inFile.open(FileName + ".txt");
if (inFile)
{
cout << FileName;
}
else
cout << "File not found, creating file.";
system("PAUSE");
return FileName;
}
void displayNumTotalAverage(string FileName)
{
ifstream inFile;
cout << "Display Number Total Average - Option 2" << endl << endl << endl;
inFile.open("C:\\Users\Wizard\Libraries\Documents\Final Project" + FileName + ".txt");
int num;
int total;
cout << "Display Number Total Average function" << FileName;
double average;
bool containsNum = false;
inFile.open(FileName + ".txt");
if (inFile)
{
while (inFile >> num)
{
cout << num << endl;
}
inFile.close();
}
else
{
cout << "Error opening file" << FileName << "." << endl;
}
system("PAUSE");
return;
}
void displaySortedNums()
{
cout << "I AM THE displaySortedNums Function - Option 3" << endl;
system("PAUSE");
return;
}
void searchNum()
{
cout << " I am the searchNum function - option 4" << endl;
system("PAUSE");
return;
}
void displayLargestNum()
{
cout << "I am the displayLargestNum Function - option 5" << endl;
system("PAUSE");
return;
}
void appendRandomNum(string FileName)
{
cout << "i am in the appendRandomNum function - option 6" << endl;
int num = 0;
int count = 0;
ofstream outFile;
outFile.open(FileName + ".txt", ios::app);
cout << "How many random numbers: ";
cin >> count;
for (int i = 0; i < count; i++)
outFile << rand() % 10 << endl;
outFile.close();
cout << endl << "Number(s) Added" << endl << endl;
system("PAUSE");
return;
}
void exit()
{
cout << " I am the exit function - option 7" << endl;
system("PAUSE");
return;
}
void CreateFile()<-----------(and this)
{
int random[50]; //Random Numbers
srand((unsigned)time(NULL));
fillFunc(random);
printFunc(random);
return;
}
void fillFunc(int arr[])
{
for (int i = 0; i < 50; i++)
{
arr[i] = 1 + rand() % 10;
}
}
void printFunc(int arr[])
{
ofstream fout("C:\\Users\Wizard\Libraries\Documents\Final Project");
if (fout.is_open()){
for (int i = 0; i < 50; i++)
{
fout << arr[i] << std::endl;
}
}
}
Assuming you have the tmp folder in your project directory, and pretending the path is: C:\Project\tmp\. This file fails to open: ofstream fout("/tmp/nums.txt");
The first slash is an error. It's as if you tried to open C:\Project\\tmp\.
If you are using Windows, it's like if you changed directory to C:\Project in command promt and then used the command cd \tmp which would result in:
The system cannot find the path specified.
Therefore, omit the first slash and let it be: ofstream fout("tmp/nums.txt"); and it will work. (I assume you're including <fstream> and that you're using the namespace std.)
there are several issues in your original code:
1) you didn't create any text file to output. Are you trying to output using ">" ?
2) you are generating 49 numbers only. To get 50, you need start from 0 instead 1. (int i=0; )
3) You don't have any delimiter in your output. How do you expect to use them?
change your printFunc to something like this:
ofstream fout ("/tmp/nums.txt");
if(fout.is_open() ){
for (int i = 0; i < 50; i++)
{
fout << arr[i] << std::endl;
}
Include fstream #include <fstream>
In printFunc change:
ofstream fout("/tmp/nums.txt");
to
ofstream fout("folder/inner_folder/file.txt", ofstream::out);
The second parameter is the mode for the file. ofstream::out means write access (which is always set for ofstream objects).
At the end of the function close the stream like so:
fout.close();
For reference: http://www.cplusplus.com/reference/fstream/ofstream/ofstream/

Saving c++ array of struct to file and issue for adding new elements to it

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.

C++ Input Into Structure: _getch()

In C++, I'm trying to input movie's names and years of releasing and store them in a database/structure. Before I ask for the titles and years to be inputted. I have the user log on with credentials. In this case, the username is "rusty" and the password is "rusty".
The issue I'm having is the after the credentials are verified, the first movie title to input into the database/structure is skipped. I believe this has something to do with me using the _getch function, but I'm not totally sure.
My code is below. My output looks like this:
Please enter your username
rusty
Please enter your password
Access granted! Welcome rusty
Enter title: Enter year: (input movie year)
Enter title: (input movie title)
Enter year: (input movie year)
Enter title: (input movie title)
....
#include <iostream>
#include <string>
#include <sstream>
#include <conio.h>
using namespace std;
//function prototype
int username_and_pass();
#define NUM_MOVIES 6
struct movies_list{
string title;
int year;
}films[NUM_MOVIES];
// prototype with function declaration
void sort_on_title(movies_list films[], int n)
{
movies_list temp;
for (int i = 0; i < n - 1; i++)
{
if (films[i].title>films[i + 1].title)
{
temp = films[i];
films[i] = films[i + 1];
films[i + 1] = temp;
}
}
}// end of sort_on_title function
void printmovie(movies_list movie)
{
cout << movie.title;
cout << " (" << movie.year << ") \n";
}
void search_on_title(movies_list films[], int n, string title)
{
bool flag = false;
for (n = 0; n < NUM_MOVIES; n++)
{
if (films[n].title == title)
{
cout << "Title: " << films[n].title << endl;
cout << "Year of Release: " << films[n].year << endl;
cout << "\n";
flag = true;
}
}
if (flag == false)
cout << "Search on title not found!" << endl;
}// end of search_on_title function
void search_on_year(movies_list films[], int n, int year)
{
bool flag = false; // check on existence of record
for (n = 0; n < NUM_MOVIES; n++)
{
if (films[n].year == year) // display if true
{
cout << "Title: " << films[n].title << endl;
cout << "Year of Release: " << films[n].year << endl;
cout << "\n";
flag = true;
}
}
if (flag = false)
cout << "Search on title not found!" << endl;
}// end of search_on_title function
int menu()
{
int choice;
cout << " " << endl;
cout << "Enter 1 to search on titles " << endl;
cout << "Enter 2 to search on years " << endl;
cin >> choice;
cout << "\n";
return choice;
}// end of menu function
int username_and_pass()
{
string uName;
string password;
int value;
char ch;
cout << "Please enter your username\n";//"rusty"
cin >> uName;
cout << "Please enter your password\n";//"rusty"
ch = _getch();
while (ch != 13)//As long as the user doesn't press Enter
{//(enter is ASCII code 13) continue reading keystrokes from the screen.
password.push_back(ch);
cout << '*';
ch = _getch();
}
if (uName == "rusty" && password == "rusty")
{
cout << "\n\nAccess granted! Welcome " << uName << "\n\n" << endl;
value = 1
}
else
{
cout << "Invalid credentials" << endl;
value = 0;
}
return value;
}// end of username_and_pass function
int main()
{
string mystr;
int n;
string response;
int value = 0;
do
{
value = username_and_pass();
} while (value==0);
if(value==1)
{
for (n = 0; n < NUM_MOVIES; n++)
{
cout << "Enter title: ";
getline(cin, films[n].title);
cout << "Enter year: ";
getline(cin, mystr);
stringstream(mystr) >> films[n].year;
}
//sorts records
sort_on_title(films, NUM_MOVIES);
cout << "\nYou have entered these movies:\n";
for (n = 0; n < NUM_MOVIES; n++)
printmovie(films[n]);
//menu
int choice = 0;
choice = menu();
if (choice == 1)
{
string searchTerm;
cout << "What is the movie you want to search for? " << endl;
cin >> searchTerm;
cout << " " << endl;
search_on_title(films, NUM_MOVIES, searchTerm);
}
else
{
int searchTermYear;
cout << "What is the year you want to search for? " << endl;
cin >> searchTermYear;
cout << " " << endl;
search_on_year(films, NUM_MOVIES, searchTermYear);
}
cout << "Would you like to query the database again? (Y/N)" << endl;
cin >> response;
if (response == "Y" || "y")
{
choice = menu();
if (choice == 1)
{
string searchTerm;
cout << "What is the movie you want to search for? " << endl;
cin >> searchTerm;
cout << " " << endl;
search_on_title(films, NUM_MOVIES, searchTerm);
}
else
{
int searchTermYear;
cout << "What is the year you want to search for? " << endl;
cin >> searchTermYear;
cout << " " << endl;
search_on_year(films, NUM_MOVIES, searchTermYear);
}
}
}
return 0;
}
Flush all the content's of input buffer.
Please go to following link to flush contents of input buffer.
https://stackoverflow.com/a/7898516/4112271
I am not sure what causing you this problem.But can you try using cin.clear(). Place it before you ask for input of title.
cin.clear();
cout << "Enter title: ";
getline(cin, films[n].title);
cout << "Enter year: ";
getline(cin, mystr);
stringstream(mystr) >> films[n].year;