C++

closed account (4zU54iN6)
hello there, i am writing a code for phone book.
i am trying to add new contacts but only latest added contact is saved.
here is my code..

#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;

class dir
{
public:
char name[20];
char num[7];
void get()
{
ofstream out;
out.open("directory", ios::out);
if(!out) {
cout << "Cannot open file.\n";
}
cout<<" enter the name"<<endl;
cin>> name;
cout<<" enter number"<<endl;
cin>> num;
out<<name<<setw(20)<<num<<endl;
out.close();
}

void show()
{
ifstream in;
in.open("directory",ios::in);
if(!in){
cout<<"Cannot open file.\n";
}
in.seekg(0,ios::beg);
cout<<"\n Records in phone directory \n";
while(in)
{
if(in)
{ in>>name>>num;
cout<<setw(20)<<name<<"\t";
cout<<setw(15)<<num;
}
}
}


};

int main()
{
int a , b;
dir d1;
char ch, name[20], num[7];
cout<<"hello, "<<endl;
cout<<"press "<<endl;
cout<<"1 to store a new contact"<<endl;
cout<<"2 to diplay all contacts"<<endl;
cout<<"3 to find number for a name "<<endl;
cout<<"4 to find name for a number"<<endl;
cout<<"5 to update a contact(number)"<<endl;
cout<<"6 exit";
cin>>a;
switch(a)
{
case 1:
d1.get();
break;
case 2:
d1.show();
break;
/* case 2:
findNum();
break;
case 3:
findName();
break;
case 4:
update();
break;
case 5:
cout<<"Exit";
break;
*/
}
cin>>b;
return 0;
}
Last edited on
1) This should be in the beginners section not the lounge(off-topic). Please edit your post and move it there.
2) What exactly is the problem/question? Is it the fact you are writing over the old file? If so you need to pass the append flag ios::app to the file. http://www.cplusplus.com/doc/tutorial/files/

Topic archived. No new replies allowed.