Code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <iomanip>
#include "contacts.h"
#define MYFILE "/Users/peterjocham/Desktop/textoutput.txt"
using namespace std;
void loadData(ifstream& fin, nodePtr &head)
{
if (fin.eof()) {
return ;
}
else
{
while (!fin.eof())
{
if (!head) {
head= new node;
getline(fin, head->name, '\n');
getline(fin, head->last, '\n');
fin>>head->age;
head->next=nullptr;
}
else
{
nodePtr curr = head;
while (curr->next)
curr=curr->next;
curr->next=new node;
fin.ignore();
getline(fin, curr->next->name, '\n');
getline(fin, curr->next->last, '\n');
fin>>curr->next->age;
curr->next->next=nullptr;
}
}
}
}
int main()
{
addressBook MyaddressBook;
ofstream outfile;
ifstream infile(MYFILE,ios::in);
int userInput=0;
nodePtr temp=new node;
string NAME;
MyaddressBook.userPromptStatement();
nodePtr head=nullptr;
loadData(infile, head);
MyaddressBook.sethead(head);
outfile.open(MYFILE,ios::app);
if (outfile.fail()) {
cerr<<"File couldn't be opened";
exit(EXIT_FAILURE);
}
while(1)
{
cin>>userInput;
if (!cin || (userInput!=1 && userInput!=2 && userInput!=3 && userInput!=4 &&userInput!=5))
{
cin.ignore();
cout<<"Only enter a 1,2,3,4, or 5"<<endl;
cout<<"You have entered an incorrect value."<<endl;
cout<<endl<<endl;
MyaddressBook.userPromptStatement();
continue;
}
switch (userInput) {
case 1:
cout<<"NAME: ";
cin.ignore();
getline(cin,temp->name,'\n');
cout<<"\nLAST NAME: ";
getline(cin,temp->last,'\n');
cout<<"\nAGE: ";
cin>>temp->age;
outfile<<
setw(2)<<temp->name<<"\n"
<<setw(2)<<temp->last<<"\n"
<<setw(2)<<temp->age<<"\n\n";
MyaddressBook.addContact(temp);
MyaddressBook.userPromptStatement();
cout<<"\n"<<"\n";
break;
case 2:
cout<<"Which contact would you like to delete?\n";
cin>>NAME;
MyaddressBook.deleteName(NAME);
MyaddressBook.userPromptStatement();
cout<<"\n"<<"\n";
break;
case 3:
MyaddressBook.editName(NAME);
break;
case 4:
MyaddressBook.printContactList();
MyaddressBook.userPromptStatement();
cout<<"\n"<<"\n";
break;
case 5:
outfile.close();
exit(EXIT_SUCCESS);
default:
break;
}
}
return 0;
}
I have nodPtr is a point as I will show below:
Code:
typedef struct node{
std::string name;
std::string last;
int age;
node *next;
}*nodePtr;
so I am doing *head, however yes I did need to do fin and not cin.
I tried using
Code:
stringstream convert (head->age);
and I had a few problems. So I decided to use fin>>, was I wrong in doing so?
I tired not using eof but I don't think I quite got the concept.
I got the program to work but now I am concern I am using bad programing practice.