For the time being I'll ignore the non-standard usage (such as conio.h) and focus on the problems with the fstream. Well done for having a go. Even though it isn't completely correct, you learn more by trying things for yourself than simply copying someone else's code.
Now, let's look at what you have right:
1 2
|
ofstream myfile;
myfile.open ("phone.txt", ios::out | ios::app | ios::in);
|
Some of that is right. Though it doesn't make much sense to use an output stream (ofstream) for input (ios::in). Also, having declared
myfile
, no more use is made of it, so naturally nothing happens with the file.
These lines simply don't compile for me
1 2
|
ofstream(contact[i]);
ofstream(number[i]);
|
it should have looked more like this:
|
myfile << contact[i] << '\n' << number[i] << '\n';
|
I think in order to keep things simple, two new functions might be used, for example call them
load()
and
save()
. At the start of the program, after
call the load function, like this:
Similarly, just before exiting from the program, call the save function.
So, using the existing display() function as a guide, we can write the save() function like this:
1 2 3 4 5 6 7
|
void phonebook::save()
{
ofstream fout("phone.txt");
for (int i=0; i<size; i++)
fout << contact[i] << '\n' << number[i] << '\n';
}
|
and add the function call in main() like this:
|
case 'q': t.save(); exit(0);
|
Try this, and then examine the contents of the text file to see whether it has worked.
The load() function will do something similar, using an
ifstream
as it will be used for input.
To read the name and number, I suggest to use the getline function.
http://www.cplusplus.com/reference/istream/istream/getline/