Ok So I have abit of a problem with my code that I cant seem to find the solution for. Im writing a program that will work like a phonebook for your phone. And everything that happens will be saved in a .txt file. So when the program starts it will always read from the same file and put that into class objects called "person" and then you will be able to edit/delete/add new contacts and then it gets rewriten to the file.
The problem im having right now is that I want to make more of the code into functions instead of having it all in the main folder. So as you can see from the two last functions, one should read from the file and the other should write to the file. What I want to do is to replace all the code in main() that has to do with readToFile and writeToFile. Also i would like to be able to put the writeToFile function after every case switch action like edit/delete/add. So that you dont have to choose to write to the file. It just does that automatically.
Can I somehow use pointers/references for this or how do i get access to the "person" objects in my functions.
First time asking a question here so feel free to educate me if i did something wrong.
Here is the code:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void printline(char, int);
bool name_valid(string);
class contact
{
public:
string fName, lName, adress, epost, mobileNo, birthday;
//initialize the contact by a default value
contact() : fName(""), lName(""), adress(""), epost(""), mobileNo(""), birthday("")
{}
// Write all contacts to the file.
bool writeToFile()
{
if (fName != "")
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1; //Success!!
}
else
{
cout << " Fail!" << endl;
return 0; //Fail!!
}
}
//Show all contacts
bool showAll()
{
if (fName != "")
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1; //Success!!
}
else
return 0; //Fail!!
}
// Search
bool Search(string search_word)
{
if (search_word == fName)
{
cout << "Name: " << fName << " " << lName << "\n" << "Mobilenumber: " << mobileNo << "\n" << "Adress: " << adress << "\n" << "Email: " << epost << "\n" << "Birthday: " << birthday << endl;
return 1;
}
else
return 0;
}
// Check if a name exists or not
bool name_exists(string tname)
{
if (tname == fName)
return 1;
else
return 0;
}
// The contact object is initialized by valid values
bool addContact(string new_fName, string new_lName, string new_adress, string new_epost, string new_mobileNo, string new_birthday )
{
if (fName == "")
{
fName = new_fName;
lName = new_lName;
adress = new_adress;
epost = new_epost;
mobileNo = new_mobileNo;
birthday = new_birthday;
return 1; // Success !!
}
else
return 0; // Failure !!
}
//edits the contact details
bool edit(string);
bool erase(string new_name)
{
if (new_name == fName)
{
fName = "";
lName = "";
adress = "";
epost = "";
mobileNo = "";
birthday = "";
return 1;
}
else
return 0;
}
};
// Edits the contact
bool contact::edit(string name_check)
{
string new_fName, new_lName, new_adress, new_epost, new_mobileNo, new_birthday;
if (name_check == fName)
{
cin.ignore();
cin.clear();
cout << "Enter new first name: ";
getline(cin,new_fName);
cout << "Enter new lastname: ";
getline(cin,new_lName);
cout << "Enter new adress: ";
getline(cin,new_adress);
cout << "Enter new epost: ";
getline(cin,new_epost);
cout << "Enter new birthday: ";
getline(cin,new_birthday);
fName = new_fName;
lName = new_lName;
adress = new_adress;
epost = new_epost;
birthday = new_birthday;
return 1;
}
else
return 0;
}
int main()
{
contact person[100];
ifstream infile("Phonebook.txt");
string temp_fName, temp_lName, temp_adress, temp_epost, temp_mobilNo, temp_birthday;
int counter, choice, i;
bool flag;
bool cancel_flag;
// Read from file to contact person
string ignoreName, ignoreCell, ignoreAdress, ignoreEmail, ignoreBirthday;
string fileFirstname, fileLastname, fileCell, fileAdress, fileEmail, fileBirthday;
// Goes through the text file and put all the names in the contact class
while (!infile.eof())
{
getline(infile, ignoreName, ' ');
getline(infile, fileFirstname, ' ');
getline(infile, fileLastname);
getline(infile, ignoreCell, ' ');
getline(infile, fileCell);
getline(infile, ignoreAdress, ' ');
getline(infile, fileAdress);
getline(infile, ignoreEmail, ' ');
getline(infile, fileEmail);
getline(infile, ignoreBirthday, ' ');
getline(infile, fileBirthday);
// Check if the file is empty
if (!infile)
{
break;
}
for (i = 0; i < 100; i++)
if (person[i].addContact(fileFirstname, fileLastname, fileAdress, fileEmail, fileCell, fileBirthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
}
infile.close();
ofstream outfile("Phonebook.txt");
cout << "=========== Your Phonebook ==========" << endl;
do
{
cout << "\n\n";
printline('-', 25);
cout << "1. Add Contact" << endl
<< "2. Edit Contact" << endl
<< "3. Delete Contact" << endl
<< "4. Search" << endl
<< "5. Show All Contacts" << endl
<< "6. Write All Contacts To File." << endl
<< "0. Exit" << endl << endl
<< "Your choice... ";
cin >> choice;
system("cls");
printline('-', 20);
cancel_flag = 0;
flag = 0;
counter = 0;
switch (choice)
{
case 0:
return 0;
break;
// Adds a new contact
case 1:
cout << "Add New Contact\t\t\t\tpress - to cancel" << endl;
printline('-', 25);
counter = 0;
// Loop until correct contact info is untered
do
{
flag = 0;
if (counter)
cout << "Try again \t\t\t\tpress - to cancel" << endl;
//count how many times the do-while loop executes
counter++;
cin.ignore();
cin.clear();
cout << "First Name: ";
getline(cin, temp_fName);
cout << "Last Name: ";
getline(cin, temp_lName);
cout << "Adress: ";
getline(cin, temp_adress);
cout << "Email: ";
getline(cin, temp_epost);
cout << "Mobile Number: ";
getline(cin, temp_mobilNo);
cout << "Birthday: ";
getline(cin, temp_birthday);
if (temp_fName == "-")
{
cancel_flag = 1;
break;
}
for (i = 0; i < 100; i++)
{
if (person[i].name_exists(temp_fName))
{
cout << "The name you entered is already there"
"in the phonebook, entere a different name." << endl;
flag = 1;
break;
}
}
} while (!name_valid(temp_fName) || flag);
if (cancel_flag)
{
system("cls");
break;
}
//This loop adds the contact to the phonebook
for (i = 0; i < 100; i++)
if(person[i].addContact(temp_fName, temp_lName, temp_adress, temp_epost, temp_mobilNo, temp_birthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
if (!flag)
cout << "Memory full! Delete some contacts first." << endl;
break;
// Edits an existing contact
case 2:
cout << "Enter a contact name to edit \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
for (i = 0; i < 100; i++)
if (person[i].edit(temp_fName))
{
cout << "Edited Successfully!" << endl;
flag = 1;
break;
}
if (!flag)
cout << "Contact name not found!" << endl;
break;
//Delete a contact
case 3:
do
{
if (counter)
cout << "Try again" << endl;
counter++;
cout << "Enter a contact name to delete: \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
//Final Confirmation
for (i = 0; i < 100; i++)
if (person[i].name_exists(temp_fName))
{
flag = 1;
cout << "Are you sure you want to delete (1/0)" << endl;
int yes;
cin >> yes;
if (!yes)
{
system("cls");
cancel_flag = 1;
}
break;
}
if (!flag)
cout << "Contact name not found!" << endl;
if (cancel_flag)
break;
// This code deletes the contact
if (flag)
{
for (i = 0; i < 100; i++)
if (person[i].erase(temp_fName))
{
cout << "Deleted successfully!" << endl;
break;
}
}
} while (!flag);
break;
// Search a contact
case 4:
do
{
if (counter)
cout << "Try again" << endl;
counter++;
cout << "Search a name: \t\t\t\tpress - to cancel" << endl;
cin >> temp_fName;
// Cancel operation
if (temp_fName == "-")
{
system("cls");
break;
}
for (i = 0; i < 100; i++)
if (person[i].Search(temp_fName))
{
flag = 1;
break;
}
if (!flag)
cout << "Contact namew not found!" << endl;
} while (!flag);
break;
// Show all the contacts
case 5:
cout << "Showing Contacts" << endl;
printline('-', 25);
for (i = 0; i < 100; i++)
{
if (person[i].showAll())
{
flag = 1;
cout << "\n\n";
}
}
if (!flag)
cout << "No contacts found!" << endl;
break;
case 6:
// Write to file
cout << "Writing to file." << endl;
printline('-', 25);
for (int i = 0; i < 100; i++)
{
if (person[i].fName != "")
{
outfile << "Name: " << person[i].fName << " " << person[i].lName << "\n" << "Mobilenumber: " << person[i].mobileNo << "\n" << "Adress: " << person[i].adress << "\n" << "Email: " << person[i].epost << "\n" << "Birthday: " << person[i].birthday << "\n\n\n\n";
flag = 1;
cout << "\n\n";
}
}
break;
}
}while (1);
return 0;
}
//prints a line
void printline(char ch, int size)
{
for (int i = 0; i < size; i++)
cout << ch;
cout << "\n";
}
//Contact name validation
bool name_valid(string tname)
{
if (tname.size() > 20)
{
cout << "Invalid name!\nEnter a name within 20 characters!" << endl;
return 0;
}
else if (tname == "")
{
cout << "Invalid Name!\nName cannot be blank" << endl;
return 0;
}
else
return 1;
}
void writeToFile()
{
cout << "Writing to file." << endl;
printline('-', 25);
for (int i = 0; i < 100; i++)
{
if (person[i].fName != "")
{
outfile << "Name: " << person[i].fName << " " << person[i].lName << "\n" << "Mobilenumber: " << person[i].mobileNo << "\n" << "Adress: " << person[i].adress << "\n" << "Email: " << person[i].epost << "\n" << "Birthday: " << person[i].birthday << "\n\n\n\n";
flag = 1;
cout << "\n\n";
}
}
}
void readfromfile()
{
ifstream infile("Phonebook.txt");
string ignoreName, ignoreCell, ignoreAdress, ignoreEmail, ignoreBirthday;
string fileFirstname, fileLastname, fileCell, fileAdress, fileEmail, fileBirthday;
// Goes through the text file and put all the names in the contact class
while (!infile.eof())
{
getline(infile, ignoreName, ' ');
getline(infile, fileFirstname, ' ');
getline(infile, fileLastname);
getline(infile, ignoreCell, ' ');
getline(infile, fileCell);
getline(infile, ignoreAdress, ' ');
getline(infile, fileAdress);
getline(infile, ignoreEmail, ' ');
getline(infile, fileEmail);
getline(infile, ignoreBirthday, ' ');
getline(infile, fileBirthday);
// Check if the file is empty
if (!infile)
{
break;
}
for (int i = 0; i < 100; i++)
if (person[i].addContact(fileFirstname, fileLastname, fileAdress, fileEmail, fileCell, fileBirthday))
{
cout << "\nContact added successfully!" << endl;
flag = 1;
break;
}
}
infile.close();
}
Just pass in an array to the function (and others which are needed). Now the size of the array is known beforehand so we can protect it from array decay too. It'll look something like this,
void writeToFile(contact(&person)[100], std::fstream& outfile, bool& flag) { ... }
void readfromfile(contact(&person)[100], bool& flag) { ... }
Note that were passing in the others (flag and outfile) using the reference so that the actual variable can be altered.
From the two, I would recommend using the second option. Its clean, simple and safe (if you may).
Note: Try not to use using namespace std;. It not a good practice and basically your taking the std namespace and putting it in the global namespace. Now that namespace is huuuuggeeeeee. Later to access its objects and stuff, use :: operator.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I tried my best to figure this out but it was unsuccessful :C
PROBLEM
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
treniruotes.remove(t);
}
}
}
FULL CODE:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <list>
#include <ctime>
using namespace std;
struct Treniruote
{
string data, laikas, vardas, pavarde, pratimai;
};
void NuskaitytiIsFailo(list<Treniruote>& treniruotes)
{
string line, word;
fstream file("planas.csv", ios::in);
if (file.is_open())
{
while (getline(file, line))
{
stringstream str(line);
Treniruote row;
if (getline(str, word, ','))
row.data = word;
if (getline(str, word, ','))
row.laikas = word;
if (getline(str, word, ','))
row.vardas = word;
if (getline(str, word, ','))
row.pavarde = word;
if (getline(str, word, ','))
row.pratimai = word;
treniruotes.push_back(row);
}
}
else
cout << "Could not open the file";
}
void rastiKlientoInfo(list<Treniruote>& treniruotes)
{
int a;
string fname, pavarde;
cout << "Write clients surname:";
cin >> pavarde;
cout << "Output to the screen press -1\n";
cout << "Output to the file press - 2\n";
cout << "Output all exercise needed to be done in a week - 3\n";
cout << "Your choice:";
cin >> a;
if (a == 2)
{
cout << "Enter the file name: ";
cin >> fname;
}
else if (a == 3)
{
cout << "Enter the file name: ";
cin >> fname;
}
else
{
}
for (Treniruote& t : treniruotes)
{
if (t.pavarde == pavarde)
{
if (a == 1)
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
else if (a == 3)
{
fstream file(fname + ".csv", ios::app);
file << t.pratimai << endl;
}
else
{
fstream file(fname + ".csv", ios::app);
file << t.data << endl;
file << t.laikas << endl;
file << t.vardas << endl;
file << t.pavarde << endl;
file << t.pratimai << endl;
file << endl;
}
}
}
}
void PakeistiReiksmes(list<Treniruote>& treniruotes)
{
string duotasLaikas, duotaData;
cout << "irasykite norima data ir laika ,kada norite pakeisti duomenys" << endl;
cout << "data(formatas(XXXX.XX.XX)):";
cin >>duotaData;
cout << endl;
cout << "laikas(formatas(XX:XX-XX:XX)):";
cin >>duotasLaikas;
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
t.vardas = t.pavarde = t.pratimai = "obolys";
}
}
}
}
void SukurtiTuscius(list<Treniruote> &treniruotes)
{
for (int i = 27; i <= 30; ++i)
{
stringstream diena;
diena << "2022.11." << i;
for (int j = 8; j <= 19; ++j)
{
stringstream valanda;
valanda << j << ":00-"<< j+1 <<":00";
Treniruote t;
t.data = diena.str();
t.laikas = valanda.str();
t.vardas = t.pavarde = t.pratimai = "nera";
treniruotes.push_back(t);
}
}
}
void ParodytiVisaTvarkarasti(list<Treniruote>& treniruotes)
{
for (Treniruote& t : treniruotes)
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
}
void salinti_pridėti(list<Treniruote>& treniruotes)
{
}
void ProgramosPabaiga(list<Treniruote>& treniruotes)
{
fstream file("planas.csv", ios::out);
for (Treniruote& t : treniruotes)
{
file << t.data <<","<< t.laikas << "," << t.vardas << "," << t.pavarde << "," << t.pratimai;
file << endl;
}
cout << "PROGRAMA BAIGTA";
exit(0);
}
int main()
{
int choice;
bool gameOn = true;
list<Treniruote> treniruotes;
struct tm newtime;
time_t now = time(0);
localtime_s(&newtime,&now);
auto month = to_string(1 + newtime.tm_mon);
auto day = to_string(newtime.tm_mday);
auto hour = to_string(newtime.tm_hour);
auto hour_pridėta = to_string(1 + newtime.tm_hour);
//sukuria .csv faila pagal irasyta pavadinima
//string fname;
//cout << "Enter the file name: ";
//cin >> fname;
// fstream file(fname + ".csv", ios::app);
//Menu
while (gameOn != false) {
cout << "*******************************\n";
cout << " 1 - Create empty weekly plan.\n";
cout << " 2 - Show the full schedule.\n";
cout << " 3 - Read the weekly work plan.\n";
cout << " 4 - Change the schedule field information.\n";
cout << " 5 - Find the given client's full weekly workouts\n";
cout << " 7 - Exit.\n";
cout << "*******************************\n";
for (Treniruote& t : treniruotes)
{
if (t.data == "2022." + month + "." + day)
{
if (t.laikas == hour + ":00-" + hour_pridėta + ":00")
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
}
}
cout << "*******************************\n";
cout << " Enter your choice and press return: ";
cin >> choice;
switch (choice)
{
case 1:
SukurtiTuscius(treniruotes);
break;
case 2:
ParodytiVisaTvarkarasti(treniruotes);
break;
case 3:
NuskaitytiIsFailo(treniruotes);
break;
case 4:
PakeistiReiksmes(treniruotes);
break;
case 5:
rastiKlientoInfo(treniruotes);
break;
case 6:
{
string duotasLaikas, duotaData;
cout << "irasykite norima data ir laika ,kada norite pakeisti langeli" << endl;
cout << "data(formatas(XXXX.XX.XX)):";
cin >> duotaData;
cout << endl;
cout << "laikas(formatas(XX:XX-XX:XX)):";
cin >> duotasLaikas;
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
treniruotes.remove(t);
}
}
}
}
break;
case 7:
{
ofstream file;
file.open("planas.csv", std::ofstream::out | std::ofstream::trunc);
file.close();
ProgramosPabaiga(treniruotes);
break;
}
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break;
}
}
return 0;
}
You must not remove items from a list while iterating through a range-based for loop. Under the hood, the loop stores a begin and end iterator of the original list, and iterate all items between them, and attempting to remove items during the loop will make end unreachable.
Instead, you could simply use std::list::remove_if to remove all elements that satisfy a certain condition:
my_list.remove_if([a, b](const auto& element){
return element.a == a && element.b == b;
};
Im writing a wordle game and am trying to get the output to work, but i have no clue as to what im doing wrong here. The basic version of the code is 5 letter words are taken from a word file and stored in an array, then a random word is picked from there to be the answer to the wordle. Then the user is prompted for input and once they input a word, it verifies the length, as well as if it is in the array of words. then another function takes the guessed word and compares it against the winning word and outputs the guessed word with colors to show what letters are in the right spot, like real wordle. The issue arises when i try to print everything out, i tried to use a while loop to ask for input but i couldnt get it to work so i decided to test it by making a function that asks for the input, then i called it six times, each time giving it a different variable to store the result in, then print out the first one on the first guess, the first and second on the second guess, and so on. But it only prints out the current guess. It might be something very obvious but i have spent so much time coding i have no idea. any help is greatly appreciated.
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
using namespace std;
const string CORRECT = "\033[7;32m";
const string CLOSE = "\033[7;33m";
const string INCORRECT = "\033[7;37m";
const string END = "\033[0m";
int verifyExists(string word, string verifyArr[2315]) {
if (word.size() == 5)
{
for (int i = 0; i < 2315; i++)
{
if (word == verifyArr[i])
{
return 1;
}
}
return 2;
} else {
return 3;
}
}
string buildResult(string plyrGuess, string word)
{
string result[5];
string color;
for (int i = 0; i < 5; i++){
if (plyrGuess[i] != word[i])
{
color = INCORRECT + plyrGuess[i] + END;
result[i] = color;
}
if ((plyrGuess[i] != word[i]) && (plyrGuess[i] == word[0] || plyrGuess[i] == word[1] || plyrGuess[i] == w\
ord[2] || plyrGuess[i] == word[3] || plyrGuess[i] == word[4]))
{
color = CLOSE + plyrGuess[i] + END;
result[i] = color;
}
if (plyrGuess[i] == word[i])
{
color = CORRECT + plyrGuess[i] + END;
result[i] = color;
}
}
string done;
for (int i = 0; i < 5; i++)
{
cout << result[i];
}
getline(cin, done);
return done;
}
string askInput(string array[2315])
{
string guessWord;
cout << "What word would you like to guess?" << endl;
getline(cin, guessWord);
while (verifyExists(guessWord, array) == 2)
{
cout << "The word: " << guessWord << " is not in the word list" << endl;
getline(cin, guessWord);
}
while (verifyExists(guessWord, array) == 3)
{
cout << "You must enter a word that is 5 letters in length: " << endl;
getline(cin, guessWord);
}
return guessWord;
}
void playGame(string winWord, string arr[2315]) {
cout << "Ok. I am thinking of a word with 5 letters." << endl;
string guess1 = askInput(arr);
string done1 = buildResult(guess1, winWord);
cout << done1 << "\n" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess2 = askInput(arr);
string done2 = buildResult(guess2, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess3 = askInput(arr);
string done3 = buildResult(guess3, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << "_____" << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess4 = askInput(arr);
string done4 = buildResult(guess4, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << done4 << endl;
cout << "_____" << endl;
cout << "_____" << endl;
string guess5 = askInput(arr);
string done5 = buildResult(guess5, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << done4 << endl;
cout << "_____" << endl;
string guess6 = askInput(arr);
string done6 = buildResult(guess6, winWord);
cout << done1 << endl;
cout << done2 << endl;
cout << done3 << endl;
cout << done4 << endl;
cout << done5 << endl;
cout << done6 << endl;
}
int main() {
string wordArray[2315];
ifstream myfile ("proj1_data.txt");
cout << " Welcome to UMBC Wordle" << endl;
if (myfile.is_open())
{
string word;
int loop = 0;
while (getline(myfile, word))
{
wordArray[loop++] = word;
}
cout << " " << endl;
cout << " Your file was imported!" << endl;
cout << " 2315 Words imported" << endl;
cout << " " << endl;
myfile.close();
}
srand(time(0));
string chosenWord = wordArray[rand() % 2315];
playGame(chosenWord, wordArray);
return 0;
}
I dont get any errors when i compile it so i know that nothings "wrong" with the code, the problem is in the playGame function, i included the whole code in case that helps
This function is to count the number of lines in my text file
int counter()
{
int counter = 0;
ifstream infile("books.txt", ios::in);
if (infile.is_open() && !infile.eof())
{
char line[200];
while (!infile.eof())
{
infile.getline(line, 200, '\n');
counter++;
}
infile.close();
}
else
cout << "File is not open\n";
return counter;
}
This is my search function where it reads data in from text file "books.txt" into array of struct - DATA book. But I couldn't figure which part is wrong and makes it show "Record not found" even if I entered the correct input. DATA book is my array of struct to store whatever is in the text file and categorized them into members like isbn code, author, title etc.
int search(DATA book[])
{
char search[200];
int i = 0;
bool found = false;
cout << "Enter ISBN Code/title/author to SEARCH: ";
cin.getline(search, 200);
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
int count = counter();
while (i < count && !found)
{
if (strcmp(search, book[i].isbn_code) == 0 || strcmp(search, book[i].author) == 0 || strcmp(search, book[i].title) == 0)
{
found = true;
cout << "ISBN Code: " << book[i].isbn_code << "\nAuthor: " << book[i].author << "\nTitle: " << book[i].title << "\nPublisher: " << book[i].publisher
<< "\nYear Published: " << book[i].year_published << "\nQuantity: " << book[i].quantity << fixed << setprecision(2)
<< "\nPrice: " << book[i].price << "\nRack: " << book[i].loc.rack << "\nLevel number: " << book[i].loc.level_no << endl << endl;
}
else
i++;
}
if (!found)
cout << "Record not found.\n";
return 0;
}
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;
});
Every time I do anything, and my while(1) gets called in my main function, my file gets cleared. It's driving me crazy. I've tried EVERYTHING. I try to put my ofstream out("data.dat"); outside the while(1) statement so it isn't called everytime but then nothing is written to the file like the ofstream isn't even working!
I've tried to make the ofstream static, so it isn't called over and over again like:
static ofstream open("data.dat");
That doesn't work.
And like I said, when I put the ofstream OUTSIDE the while statement, nothing is written to the file. Like:
ofstream out("data.dat");
while (1)
{
string line = "";
cout << "There are currently " << structList.size() << " items in memory.";
cout << endl << endl;
cout << "Commands: " << endl;
cout << "1: Add a new record " << endl;
cout << "2: Display a record " << endl;
cout << "3: Edit a current record " << endl;
cout << "4: Delete a record " << endl;
cout << "5: Save current information " << endl;
cout << "6: Exit the program " << endl;
cout << endl;
cout << "Enter a command 1-6: ";
getline(cin , line);
int rValue = atoi(line.c_str());
system("cls");
switch (rValue)
{
case 1:
structList = addItem(structList);
break;
case 2:
displayRecord(structList);
break;
case 3:
structList = editRecord(structList);
break;
case 4:
deleteRecord(structList);
break;
case 5:
if (!structList.size()) { cout << "There are no items to save! Enter one first!" << endl << endl; system("pause"); system("cls"); break; }
writeVector(out , structList);
break;
case 6:
return 0;
default:
cout << "Command invalid. You can only enter a command number 1 - 6. Try again. " << endl;
}
out.close();
}
And can someone tell me why my check to prevent reading of a empty file won't work?
My Check:
bool checkFileEmpty()
{
ifstream in("data.dat");
if (in.peek() == in.eofbit)
{
return true;
}
return false;
}
I am so sick and tired of my program crashing on startup over and over again because my vector is getting set to a size of 200 million. I've tried a BUNCH of stuff for this... none of it works... Please GOD someone help me with both of these! I've been up for 18 hours working on this ( all night yes ) and i'm ALMOST done. I'm begging you....
My Code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace System;
using namespace std;
#pragma hdrstop
bool isValidChoice(int size, int choice);
bool checkFileEmpty();
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);
template<typename T>
vector<T> readVector(ifstream &in);
template<typename T>
vector<T> addItem(vector<T> &vec);
template<typename T>
void printItemDescriptions(vector<T> &vec);
template<typename T>
int displayRecord(vector<T> &vec);
template<typename T>
vector<T> editRecord(vector<T> &vec);
template<typename T>
vector<T> deleteRecord(vector<T> &vec);
struct InventoryItem {
string Description;
int Quantity;
int wholesaleCost;
int retailCost;
string dateAdded;
} ;
int main(void)
{
cout << "Welcome to the Inventory Manager extreme! [Version 1.0]" << endl;
ifstream in("data.dat");
if (in.is_open()) { cout << "File \'data.dat\' has been opened successfully." << endl; } else { cout << "Error opening data.dat" << endl;}
cout << "Loading data..." << endl;
vector<InventoryItem> structList = readVector<InventoryItem>( in );
cout <<"Load complete." << endl << endl;
in.close();
while (1)
{
string line = "";
cout << "There are currently " << structList.size() << " items in memory.";
cout << endl << endl;
cout << "Commands: " << endl;
cout << "1: Add a new record " << endl;
cout << "2: Display a record " << endl;
cout << "3: Edit a current record " << endl;
cout << "4: Delete a record " << endl;
cout << "5: Save current information " << endl;
cout << "6: Exit the program " << endl;
cout << endl;
cout << "Enter a command 1-6: ";
getline(cin , line);
int rValue = atoi(line.c_str());
system("cls");
ofstream out("data.dat");
switch (rValue)
{
case 1:
structList = addItem(structList);
break;
case 2:
displayRecord(structList);
break;
case 3:
structList = editRecord(structList);
break;
case 4:
deleteRecord(structList);
break;
case 5:
if (!structList.size()) { cout << "There are no items to save! Enter one first!" << endl << endl; system("pause"); system("cls"); break; }
writeVector(out , structList);
break;
case 6:
return 0;
default:
cout << "Command invalid. You can only enter a command number 1 - 6. Try again. " << endl;
}
out.close();
}
system("pause");
return 0;
}
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
out << vec.size();
for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
{
out << *i;
}
cout << "Save completed!" << endl << endl;
}
ostream &operator<<(ostream &out, const InventoryItem &i)
{
out << i.Description << ' ';
out << i.Quantity << ' ';
out << i.wholesaleCost << ' ' << i.retailCost << ' ';
out << i.dateAdded << ' ';
return out;
}
istream &operator>>(istream &in, InventoryItem &i)
{
in >> i.Description;
in >> i.Quantity;
in >> i.wholesaleCost >> i.retailCost;
in >> i.dateAdded;
return in;
}
template<typename T>
vector<T> readVector(ifstream &in)
{
size_t size;
if (checkFileEmpty())
{
size = 0;
} else {
in >> size;
}
vector<T> vec;
vec.reserve(size);
for(unsigned int i = 0; i < size; i++)
{
T tmp;
in >> tmp;
vec.push_back(tmp);
}
return vec;
}
template<typename T>
vector<T> addItem(vector<T> &vec)
{
system("cls");
string word;
unsigned int number;
InventoryItem newItem;
cout << "-Add a new item-" << endl << endl;
cout << "Enter the description for the item: ";
getline (cin , word);
newItem.Description = word;
cout << endl;
cout << "Enter the quantity on hand for the item: ";
getline (cin , word);
number = atoi(word.c_str());
newItem.Quantity = number;
cout << endl;
cout << "Enter the Retail Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
newItem.retailCost = number;
cout << endl;
cout << "Enter the Wholesale Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
newItem.wholesaleCost = number;
cout << endl;
cout << "Enter current date: ";
getline (cin , word);
newItem.dateAdded = word;
vec.push_back(newItem);
return vec;
}
template<typename T>
void printItemDescriptions(vector<T> &vec)
{
int size = vec.size();
if (size)
{
cout << "---------------------------------" << endl;
cout << "| ~ Item Descriptions ~ |" << endl;
cout << "---------------------------------" << endl;
cout << "*********************************" << endl;
for (int i = 0 ; i < size ; i++)
{
cout << "(" << i+1 << ")" << ": " << vec[i].Description << endl;
}
cout << "*********************************" << endl << endl;
}
}
template<typename T>
int displayRecord(vector<T> &vec)
{
string word = "";
string quit = "quit";
int choice = 1;
int size = vec.size();
if (size)
{
printItemDescriptions(vec);
cout << endl;
while (1)
{
cout << "Type \"exit\" to return to the Main Menu." << endl << endl;
cout << "Enter \"list\" to re-display the items." << endl << endl;
cout << endl;
cout << "Pick the number of the item you would like to display: ";
getline (cin , word);
if (convertToLower(word) == "exit") { system("cls"); return 0; }
if (convertToLower(word) == "list") { system("cls"); displayRecord(vec); }
choice = atoi(word.c_str());
choice -= 1;
if (isValidChoice(size, choice))
{
system("cls");
cout << endl << "[Item (" << choice << ") details] " << endl << endl;
cout << "******************" << endl;
cout << "* Description * " << vec[choice].Description << endl;
cout << "******************" << endl << endl;
cout << "******************" << endl;
cout << "*Quantity On Hand* " << vec[choice].Quantity << endl;
cout << "******************" << endl << endl;
cout << "******************" << endl;
cout << "* Wholesale Cost * " << vec[choice].wholesaleCost << endl;
cout << "****************** " << endl << endl;
cout << "******************" << endl;
cout << "* Retail Cost * " << vec[choice].retailCost << endl;
cout << "****************** " << endl << endl;
cout << "******************" << endl;
cout << "* Data Added * " << vec[choice].dateAdded << endl;
cout << "****************** " << endl << endl;
} else { system("cls"); cout << "That item doesn't exist!" << endl; cout << "Pick another item or enter \"list\" to see available items." << endl << endl; }
}
} else { cout << "There are currently no items to display." << endl << endl; system("pause"); system("cls"); return 0; }
return 1;
}
bool isValidChoice(int size, int choice)
{
for (int i = 0 ; i <= size ; i++)
{
if (choice == i) { return true; }
}
return false;
}
string convertToLower(string word)
{
for (unsigned int i = 0 ; i < word.size() ; i++)
{
word[i] = tolower(word[i]);
}
return word;
}
bool checkFileEmpty()
{
ifstream in("data.dat");
if (in.peek() == in.eofbit)
{
return true;
}
return false;
}
template<typename T>
vector<T> editRecord(vector<T> &vec)
{
string word;
int choice;
printItemDescriptions(vec);
cout << "Choose item to edit: ";
getline ( cin, word );
choice = atoi(word.c_str());
system("cls");
unsigned int number;
InventoryItem newItem;
cout << "-Edit an item-" << endl << endl;
cout << "Enter the description for the item: ";
getline (cin , word);
vec[choice-1].Description = word;
cout << endl;
cout << "Enter the quantity on hand for the item: ";
getline (cin , word);
number = atoi(word.c_str());
vec[choice-1].Quantity = number;
cout << endl;
cout << "Enter the Retail Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
vec[choice-1].retailCost = number;
cout << endl;
cout << "Enter the Wholesale Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
vec[choice-1].wholesaleCost = number;
cout << endl;
cout << "Enter current date: ";
getline (cin , word);
vec[choice-1].dateAdded = word;
system("cls");
cout << "Item edited successfully! " << endl;
return vec;
}
template<typename T>
vector<T> deleteRecord(vector<T> &vec)
{
if (!vec.size()) { cout << "There are no items to delete!" << endl << endl; return vec; }
printItemDescriptions(vec);
string word;
int choice;
cout << "Choose item to delete: ";
getline( cin, word);
choice = atoi(word.c_str());
vec.erase (vec.begin()+choice-1);
return vec;
}
You'd better move the ofstream openning and closing inside case 5.
Here you create a new file at each while iteration.
case 5:
{
ofstream out("data.dat");
writeVector(out , structList);
out.close();
}
break;
ofstream out("data.dat");
Opens the file for writing. By default, it will start at the very beginning wiping out anything that was there previously. First, use a different output file than the file you are reading from.
Try adding the close to the case 6 statements:
case 6:
out.close();
return 0;
I'm pretty sure the close isn't getting called as the return will exit main before getting to that statement. With the file unclosed you are left with a buffer unflushed and I suspect that will leave the data unwritten.
You should move the open to before the while loop and also remove the out.close() from the while loop as it's going to close the file after the first menu selection.
To check if a file is empty or cannot be opened
bool IsEmpty( const std::string & filename ) {
std::ifstream ifs( filename.c_str() );
if ( ifs.is_open() ) {
std::string line;
return ! std::getline( ifs, line );
}
else {
return true;
}
}