Splitting lines from an external text file in to a structure? - c++

I really have no idea, how to explain this question. But here it is...
Suppose I have an external text file, and it's content goes like this:
1 Crysis 2012 Crytek Ubisoft
2 FarCry 2009 Crytek Ubisoft
3 Need_For_Speed 1695 EA Ubisoft
4 Assassin'sCreed 2008 Ubisoft Ubisoft
5 COD 2010 Activision Ubisoft
then i've used this code:
if (fout.is_open())
{
std::string delim = " ";
size_t pos = 0;
std::string token;
while (getline(fout, line))
{
while ((pos = line.find(delim)) != std::string::npos)
{
token = line.substr(0, pos);
std::cout << token << std::endl;
line.erase(0, pos + delim.length());
}
std::cout << line << std::endl;
}
}
this code splits the text lines and outputs the following
1
Crysis
2012
Crytek
Ubisoft
2
FarCry
2009
Crytek
Ubisoft
3
Need_For_Speed
1695
EA
Ubisoft
4
Assassins'sCreed
2008
Ubisoft
Ubisoft
5
COD
2010
Activision
Ubisoft
What I actually want is to create a new structure in each loop and create it's 5 variables to hold each of the porperties for every individual game. For Example
struct Game
{
int id;
string title;
int year;
string developer;
string publisher;
};
Now from the output:
1
Crysis
2012
Crytek
Ubisoft
As the loop runs I want to create a new "Game" Structure and assign these values to it's variables and then push the structure in to a vector.
Here is a summary of what I am trying to create and how far I have come:
The program is a database of games. The user is able to add,delete,search and edit any item from the database. As the program runs and the user adds a Game it successfully gets written in the external .txt file and also get pushed to the end of the vector. Now that is all fine. But when I close the program and run it again, there is data in the text file but the vector is empty. So i want the vector to get populated again with the data in the .txt file, so that the user can continue working with the database.
I dont know if I explained the problem well enough. Or I might have over explained it. I am actually a noob in C++.
Thanks in advance..
here is the full code for the program i am working on...
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Game
{
int id;
int year;
string title;
string publisher;
string developer;
};
void ShowData(vector<Game> myDatabase)
{
cout << endl;
for(size_t i = 0; i <= myDatabase.size()-1; i++)
{
cout << endl;
cout << "-------------------------------------------------------"<<endl;
cout << " ITEM NO" << " " << i + 1 << " " <<endl;
cout << "-------------------------------------------------------"<<endl;
cout << " TITLE: " << myDatabase[i].title << endl;
cout << " YEAR: " << myDatabase[i].year << endl;
cout << "DEVELOPER: " << myDatabase[i].developer << endl;
cout << "PUBLISHER: " << myDatabase[i].publisher << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
string option;
int serialNumber = 0;
int count = 0;
string line;
vector<Game> Database;
fstream fout;
fout.open("Database.txt");
if (fout.is_open())
{
std::string delim = " ";
size_t pos = 0;
std::string token;
while (getline(fout, line))
{
Game newGame;
std::cout << line << std::endl;
}
while (getline(fout, line))
{
while ((pos = line.find(delim)) != std::string::npos)
{
token = line.substr(0, pos);
std::cout << token << std::endl;
line.erase(0, pos + delim.length());
}
std::cout << line << std::endl;
}
}
else
{
cout << "There was an error opening the file.";
}
cout << endl;
repeat:
cout << endl;
cout << "ADD | SHOW | DELETE | EDIT | SEARCH " << endl;
cout << "SAY : ";
cin >> option;
if(option == "ADD" || option == "Add" || option == "add")
{
serialNumber += 1;
Game NewGame;
NewGame.id = serialNumber;
cout << endl << "Name: ";
cin >> NewGame.title;
cout << "Year: ";
cin >> NewGame.year;
cout << "Developer: ";
cin >> NewGame.developer;
cout << "Publisher: ";
cin >> NewGame.publisher;
cout << endl;
Database.push_back(NewGame);
cout << endl;
cout << "Size is: " << Database.size();
fout << serialNumber << " " << Database[Database.size() - 1].title << " " << Database[Database.size() - 1].year << " "<< Database[Database.size() - 1].developer << " " << Database[Database.size() - 1].publisher << endl;
goto repeat;
}
if (option == "SHOW" || option == "Show" || option == "show")
{
ShowData(Database);
goto repeat;
}
if(option == "DELETE" || option == "Delete" || option == "delete")
{
int choose;
cout << "Delete Item No: ";
cin >> choose;
Database.erase(Database.begin() + (choose - 1));
cout << endl;
ShowData(Database);
goto repeat;
}
if(option == "SEARCH" || option == "Search" || option == "search")
{
cout << "Search By [ID, TITLE, YEAR, DEVELOPER, PUBLISHER] : ";
string choose;
cin >> choose;
if(choose == "ID" || choose == "Id" || choose == "id")
{
int idNumber;
cout << "ID No: ";
cin >> idNumber;
cout << endl;
cout << "ITEM NO" << "[" << idNumber << "]" <<endl;
cout << " TITLE: " << Database[idNumber - 1].title << endl;
cout << " YEAR: " << Database[idNumber - 1].year << endl;
cout << "DEVELOPER: " << Database[idNumber - 1].developer << endl;
cout << "PUBLISHER: " << Database[idNumber - 1].publisher << endl;
goto repeat;
}
else if (choose == "TITLE" || choose == "Title" || choose == "title")
{
string whatTitle;
cout << "Enter Title: ";
cin >> whatTitle;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].title == whatTitle)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
else if (choose == "YEAR" || choose == "Year" || choose == "year")
{
int whatYear;
cout << "Enter Year: ";
cin >> whatYear;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].year == whatYear)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
else if (choose == "DEVELOPER" || choose == "Developer" || choose == "developer")
{
string whatDeveloper;
cout << "Enter Developer Name: ";
cin >> whatDeveloper;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].developer == whatDeveloper)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
else if (choose == "PUBLISHER" || choose == "Publisher" || choose == "publisher")
{
string whatPublisher;
cout << "Enter Publisher Name: ";
cin >> whatPublisher;
for(size_t i = 0; i <= Database.size()-1; i++)
{
if(Database[i].publisher == whatPublisher)
{
cout << endl;
cout << "ITEM NO" << "[" << i + 1 << "]" <<endl;
cout << " TITLE: " << Database[i].title << endl;
cout << " YEAR: " << Database[i].year << endl;
cout << "DEVELOPER: " << Database[i].developer << endl;
cout << "PUBLISHER: " << Database[i].publisher << endl;
}
}
goto repeat;
}
}
if (option == "EDIT" || option == "Edit" || option == "edit")
{
int whichItem;
cout << "Enter Item No: ";
cin >> whichItem;
cout << endl << "Name: ";
string name;
cin >> name;
Database[whichItem - 1].title = name;
cout << "Year: ";
int year;
cin >> year;
Database[whichItem - 1].year = year;
cout << "Developer: ";
string developer;
cin >> developer;
Database[whichItem - 1].developer = developer;
cout << "Publisher: ";
string publisher;
cin >> publisher;
Database[whichItem - 1].publisher = publisher;
cout << endl;
ShowData(Database);
goto repeat;
}
fout.close();
system("PAUSE");
return 0;
}

You can create a struct as shown here.
In the example, they have an array of structs. In order to access an element of the struct use the . operator.
In C++11, you can use a tuple, instead of a struct.
Tuple vs Struct - Stackoverflow.
The idea is that the first can provide more generic operations, while the second has far better readability and you do not have to remember the order of your data members, IMHO.
[EDIT]
AS R. Hasan states, the question is a duplicate of this question.

I am not sure that's what you are looking for, but consider this (and don't forget to include vector)
First, we define custom structure
struct Game //your structure
{
int id;
std::string title;
int year;
std::string developer;
std::string publisher;
};
Now we overload operator>> (it's similar to using cin >> someVariable). Fstream already has methods to write in variables of standard types.
bool operator>>(std::fstream& fs, Game& g)
{
if (fs >> g.id >> g.title >> g.year >> g.developer >> g.publisher)
return true;
return false;
}
/*
fs >> g.id >> g.title equals (fs.operator>>(g.id)).operator>>(g.title) ...
*/
Standard operator>> returns reference to fstream, so we are able to write everything in just 1 line of code. If writing does fail (e.g. end of file reached) we return false.
std::vector<Game> vec;
STL vector
- standard container, that contains your Game structs
if (fout.is_open())
{
for ( ; ; )
{
Game g; //creating instantiation of your struct Game
if (fout >> g) //reading from your file
vec.push_back(g); //1 of STL vector methods, check link to cppreference higher
else //if reading fails, we break our infinite loop
break;
}
}
for (auto x : vec) //going through every element of our vector.
cout << x.id << " "; //and printing first variable of your structure

Related

How to move back and forth in array list C++?

So I want to search my array for my data and move back and forth, so this is what i came up with, however this isn't working, can there be a better way to do this ? I tried to google some tips however I wasn't finding a suitable way to do this...
Can binary search be used to do this same thing ?
struct student
{
int stid = NULL;
char stname[15] = "NULL";
int grades = NULL;
string date = NULL;
};
int main()
{
int choose = 0;
int stid = 0;
int array = 1;
struct student s[1] = { 001, "Sara", "123456", "Canada", "02/01/2019" };
while (choose != 4)
{
cout << "1. Add\n";
cout << "2. View\n";
cout << "3. Search\n";
cout << "4. Quit\n";
cin >> choose;
if (choose == 3)
{
cout << "How would you like to find the Student Details?" << endl;
cout << "1 - By student id " << endl;
int choice = 0;
cin >> choice;
if (choice == 1)
{
cout << "Student ID: ";
cin >> stid;
for (int i = 0; i < array; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
while (true)
{
cout << "Which record do you wish to see?" << endl;
cout << " 1 : Forth " << endl;
cout << " 2 : Back " << endl;
int choice = 0;
cin >> choice;
if (choice == 1)
{
stid = stid + 1;
for (int i = 0; i == stid; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
}
}
}
else if (choice == 2)
{
stid = stid - 1;
for (int i = 0; i == stid; i++)
{
if (s[i].stid == stid)
{
cout << "ID: " << s[i].stid << "\n";
cout << "Name: " << s[i].stname << "\n";
cout << "Grades: " << s[i].grades << "\n";
cout << "Date joined school: " << s[i].date<< "\n";
}
}
}
Thank you for helping.

c++ function deleting a line

hello guys i'm trying to delete a full line from a ".txt" file when the user enters the book id
my text file looks like this :
[BOOK INFO]%Book Id : 1%title : Object oriented programming%[PUBLISHER
INFO]%publisher name : misr publish house%puplisher address
:adfaf%[AUTHOR(s) INFO]%Authors Name : ahmed%Nationality :
egyptian%Authors Name : eter%Nationality : american%[MORE
INFO]%PublishedAt : 3/3/2006%status :6.
[BOOK INFO]%Book Id : 2%title : automate%[PUBLISHER INFO]%publisher
name : misr%puplisher address :nasr city%[AUTHOR(s) INFO]%Authors Name
: ahmed khaled%Nationality : egyptian%Authors Name : ohammed
adel%Nationality : egyptian%[MORE INFO]%PublishedAt : 3/8/2005%status
:15.
the line starts from [book info] to the (.)
i should be able to delete the whole line when the user enter the id
but i don't know how or what function to use
my code is :
/*password is admin*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include<stdlib.h>
#include<iomanip>
#include<conio.h>
#define F1 59
#define ESC 27
using namespace std;
void list_all_books_1();
void list_available_books_2();
void borrow_books_3();
void search_for_abook_4();
void add_new_book_5();
void delete_books_6();
fstream d_base;
char path[] = "library books.txt";
void output(){
//this function for displaying choices only
cout << setw(77) << "***********************************" << endl;
cout << setw(71) << "1. List all books in library" << endl;
cout << setw(77) << "2. List available books to borrow " << endl;
cout << setw(72) << "3. Borrow a Book from library" << endl;
cout << setw(63) << "4. Search For a Book" << endl;
cout << setw(59) << "5. Add New Books" << endl;
cout << setw(59) << "6. Delete a Book" << endl;
cout << setw(62) << "7. EXIT The Library" << endl;
cout << setw(77) << "***********************************" << endl;
}
//=====================================================================================================================================================
struct books{
//identfying books with all needed things
string id, status;
string title, p_name, p_address;
string date;
};
struct author{
string aut_name;
string aut_nationality;
};
//=====================================================================================================================================================
//function for choice 1 showing the books
void list_all_books_1(){
ifstream show;
char all;
show.open(path, ios::in | ios::app);
while (!show.eof()){
show >> std::noskipws;
show >> all;
if (all == '%')
cout << "\n";
else if (all == '.')
cout << "\n\n\n";
else
cout << all;
}
cout << endl;
show.close();
}
//=====================================================================================================================================================
void list_available_books_2(){
ifstream available_books;
char x;
available_books.open(path, ios::in | ios::app);
while (!available_books.eof()){
available_books >> std::noskipws;
available_books >> x;
if (x == '%')
cout << "\n";
else if (x == '.')
cout << "\n\n\n";
else
cout << x;
}
cout << endl;
available_books.close();
}
//=====================================================================================================================================================
void borrow_books_3(){
}
//=====================================================================================================================================================
void search_for_abook_4(){
string idx;
int offset, i = 0;
string line;
cout << "enter the ID of the book you're looking for";
cin >> idx;
d_base.open(path, ios::in | ios::app);
while (!d_base.eof()){
getline(d_base, line);
if (((offset = line.find(idx, 0))) != string::npos){
cout << "Book found" << endl;
i++;
d_base.close();
}
}
if (i == 0){
cout << "couldn't find book" << endl << endl;
}
}
//=====================================================================================================================================================
//for choice 5 to fill books
void add_new_book_5(){
int aut_number, booksnumber;
books newbook[1000];
author aut[100];
cout << "how many books you want to add ? ";
cin >> booksnumber;
cout << "what books you want to add :" << endl;
d_base.open(path, ios::out | ios::app);
for (int i = 0; i < booksnumber; i++){
cout << "id please : "; cin >> newbook[i].id;
cout << "title : "; cin.ignore(); getline(cin, newbook[i].title);
cout << "publisher name :"; getline(cin, newbook[i].p_name);
cout << "publisher address : "; getline(cin, newbook[i].p_address);
d_base << "[BOOK INFO]" << "%Book Id : " << newbook[i].id << "%title : " << newbook[i].title;
d_base << "%[PUBLISHER INFO]" << "%publisher name : " << newbook[i].p_name << "%puplisher address :" << newbook[i].p_address;
d_base << "%[AUTHOR(s) INFO]";
cout << "how many authors for the books";
cin >> aut_number;
for (int j = 0; j < aut_number; j++){
cout << "author" << j + 1 << " name : "; cin.ignore(); getline(cin, aut[j].aut_name);
cout << "Nationality : "; getline(cin, aut[j].aut_nationality);
d_base << "% Authors Name : " << aut[j].aut_name << "% Nationality : " << aut[j].aut_nationality;
}
cout << "Publish date :"; getline(cin, newbook[i].date);
cout << "How many copies of " << newbook[i].title << " "; cin >> newbook[i].status;
d_base << "%[MORE INFO]";
d_base << "%PublishedAt : " << newbook[i].date << "%status :" << newbook[i].status << "." << endl;
}
d_base.close();
cout <<setw(76)<< "Books Have Been Saved Sucessfully" << endl;
}
//=====================================================================================================================================================
void delete_books_6(){
//deleting a book
}
//=====================================================================================================================================================
int main(){
char choice;
cout << "\n\n" << setw(76) << "{ welcome to FCIS library }\n\n";
do{
output();
cout << "- what do you want to do ? ";
cin >> choice;
if (choice == '1'){
system("cls");
list_all_books_1();
}
//this one for list available books
else if (choice == '2'){
system("cls");
list_available_books_2();
}
//this one for borrow a book
else if (choice == '3'){
system("cls");
borrow_books_3();
}
else if (choice == '4'){
system("cls");
search_for_abook_4();
}
//this one is for adding new books to the list
else if (choice == '5'){
system("cls");
string pass;
do{
cout << "you must be an admin to add new books." << endl << "please enter passowrd (use small letters) : ";
cin >> pass;
if (pass == "b")
break;
else if (pass == "admin"){
system("cls");
cout << "ACCESS GAINED WELCOME " << endl;
add_new_book_5();
}
else{
cout << "Wrong password try again or press (b) to try another choice";
continue;
}
} while (pass != "admin");
}
//this one for deleteing a book
else if (choice == '6'){
system("cls");
//not completed yet
}
else if (choice == '7'){
system("cls");
cout << "\n\n\n"<<setw(76) << "Thanks for Using FCIS LIBRARY" << endl;
break;
}
else
cout << "\nwrong choice please choose again\n\n";
} while (_getch()!=27);
}
i tried to use get line and search for matching id the delete the line if there's match but couldn't accomplish it
i'm beginner at c++ by the way
Read the whole file into a memory buffer. Delete what you don't want. Overwrite the existing file with the contents of your memory buffer.
You've now deleted what you did not want from the file.

Is it a good idea if I put all this in a different function?

So I'm working on this endterm project. Which the teacher said that we should use functions now. Which he recently introduced to us. My question is if it's a good idea to put every option into a function? Functions are for organizing and for code reuse right? Or I'm missing the point of functions. XD
What I mean is like making a function for option 1, which is add account. Instead of putting it in the main function. So far I only made a function for options 3,4 and 5. Which are search, view and delete functions
#include <iostream>
#include <string>
using namespace std;
bool accountSearch(int searchParameter);
void viewList();
void deleteFromList(int delParameter);
int option, numberOfAccounts = 0, accountNumSearch, index, deleteAccount;
struct personAccount
{
int currentBalance, accountNumber, pin;
string lastname, firstname, middlename;
};
personAccount account[20];
int main()
{
do{
cout << "[1] Add Account" << endl
<< "[2] Edit Account" << endl
<< "[3] Search Account" << endl
<< "[4] View Account" << endl
<< "[5] Delete Account" << endl
<< "[6] Inquire" << endl
<< "[7] Change Pin Number" << endl
<< "[8] Withdraw" << endl
<< "[9] Deposit" << endl
<< "[10] View Transactions" << endl
<< "[11] Exit" << endl << endl
<< "Option [1-11]: ";
cin >> option; cout << endl;
if(option == 1)
{
if(numberOfAccounts != 20)
{
cout << "Account Number: ";
cin >> account[numberOfAccounts].accountNumber;
cout << "PIN: ";
cin >> account[numberOfAccounts].pin;
cout << "Lastname: ";
cin >> account[numberOfAccounts].lastname;
cout << "Firstname: ";
cin >> account[numberOfAccounts].firstname;
cout << "Middlename: ";
cin >> account[numberOfAccounts].middlename;
account[numberOfAccounts].currentBalance = 0;
++numberOfAccounts;
cout << endl;
}
else
{
cout << "The list is full!\n\n";
}
}
else if(option == 2)
{
if(numberOfAccounts != 0)
{
cout << "Account Number: ";
cin >> accountNumSearch;
if(accountSearch(accountNumSearch))
{
cout << "PIN: ";
cin >> account[index].pin;
cout << "Lastname: ";
cin >> account[index].lastname;
cout << "First name: ";
cin >> account[index].firstname;
cout << "Middlename: ";
cin >> account[index].middlename;
cout << endl;
}
else
{
cout << "Account not found!\n\n";
}
}
else
{
cout << "The list is empty!\n\n";
}
}
else if(option == 3)
{
if(numberOfAccounts != 0)
{
cout << "Enter account number to search: ";
cin >> accountNumSearch;
if(accountSearch(accountNumSearch))
{
cout << "Found at index " << index << "\n\n";
}
else
{
cout << "Not found!\n\n";
}
}
else
{
cout << "The list is empty!\n\n";
}
}
else if(option == 4)
{
if(numberOfAccounts != 0)
{
viewList();
}
else
{
cout << "The list is empty!\n\n";
}
}
else if(option == 5)
{
if(numberOfAccounts != 0)
{
cout << "Account Number: ";
cin >> deleteAccount;
deleteFromList(deleteAccount);
}
}
}while(option != 11);
}
bool accountSearch(int searchParameter)
{
bool found = 0;
for(int i = 0; i < numberOfAccounts; i++)
{
index = i;
if (account[i].accountNumber == searchParameter)
{
found = 1;
break;
}
}
if(found)
{
return 1;
}
else
{
return 0;
}
}
void viewList()
{
for(int i = 0; i < numberOfAccounts; i++)
{
cout << "Account Number: " << account[i].accountNumber << endl
<< "Lastname: " << account[i].lastname << endl
<< "Firstname: " << account[i].firstname << endl
<< "Middlename: " << account[i].middlename << endl
<< "Current Balance: " << account[i].currentBalance << "\n\n";
}
}
void deleteFromList(int delParameter)
{
if(accountSearch(deleteAccount))
{
for(int i = index; i < numberOfAccounts; i++)
{
account[i] = account[i+1];
}
--numberOfAccounts;
cout << "Deleted Done\n";
}
else
{
cout << "Account not found!\n";
}
}
It's not done yet, but is there anything you would like to mention or suggest?
Yes, you should write functions separately, it's common good practice as a programmer, It will be easier for you(and others) to read, follow, and understand your code.
So, if your options do different things, they should have their own functions. (More like it would be desirable, in the end it's up to you)

C++ Address Book Array and Textfile

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

Addressbook writing to file

I have an Addressbook C++ program that compiles and everything, but I cannot figure out how to write it to a file that saves the data each time it exits. Here is my code:
//AddressBook Program
#include <iostream>
#include <string.h>
#include <cstdlib>
#include <stdio.h>
using namespace std;
class AddressBook{
public :
AddressBook()
{
count = 0;
}
void AddEntry();
void DisplayAll();
void DisplayEntry(int i); // Displays one entry
void SearchEntry();
int MainMenu();
struct Entry_Struct
{
char firstName[ 15 ] ;
char lastName[ 15 ] ;
char birthday[ 15 ] ;
char phone[ 15 ] ;
char email[ 15 ] ;
};
Entry_Struct entries[100];
unsigned int count;
};
void AddressBook::AddEntry()
{
cout << "Entry number " << (count + 1) << " : " << endl;
cout << "Enter First Name: ";
cin >> entries[count].firstName;
cout << "Enter Last Name: ";
cin >> entries[count].lastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].phone;
cout << "Enter Email: ";
cin >> entries[count].email;
++count; // tally total entry count
}
void AddressBook::DisplayEntry(int i)
{
cout << "Entry[" << i + 1 << "] : " << endl; // states # of entry
cout << "First name : " << entries[i].firstName << endl;
cout << "Last name : " << entries[i].lastName << endl;
cout << "Date of birth : " << entries[i].birthday << endl;
cout << "Phone number : " << entries[i].phone << endl;
cout << "Email: " << entries[i].email << endl;
}
void AddressBook::DisplayAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DisplayEntry(i);
}
void AddressBook::SearchEntry()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].lastName) == 0)
{
cout << "Found ";
DisplayEntry(i);
cout << endl;
}
}
}
// Your class
AddressBook my_book;
int MainMenu()
{
int num;
bool bQuit = false;
// Put all your code into a while loop.
while(bQuit == false)
{
cout << "+-------------------------------------+" << endl;
cout << "| Address Book Menu |" << endl;
cout << "| |" << endl;
cout << "| 1- Add an entry |" << endl;
cout << "| 2- Search for an entry by last name |" << endl;
cout << "| 3- Display all entries |" << endl;
cout << "| 4- Exit |" << endl;
cout << "| |" << endl;
cout << "+-------------------------------------+" << endl;
cout << endl;
cout << "Please enter a number for one of the above options: ";
cin >> num;
cout << endl;
if (num == 1)
my_book.AddEntry();
else if (num == 2)
my_book.SearchEntry();
else if (num == 3)
my_book.DisplayAll();
else if (num == 4)
bQuit = true;
else
cout << "Invalid choice. Please try again" << endl;
cout << endl;
}
return 0;
}
int main (){
MainMenu();
return 0;
}
I've gone over my textbook all day and nothing I'm doing is working.
Here is a basic example of opening, and writing an output file,
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream outfile;
outfile.open ("addressbook.txt");
outfile << "Daffy,Duck,123 Main Street,Anytown,OH,USA,123-456-7890\n";
myfile.close();
return 0;
}
You need to have an inserter for your class. It's done using operator <<:
// Inside your class:
friend std::istream& operator<<(std::ostream& os, const AddressBook ab)
{
return os << /* ... */
}
As you can see, a user-defined operator << can be implemented in terms of the pre-defined standard inserter. You can use it in the following way:
std::ifstream in("yourtxtfile.txt");
in << my_book;