Reading and right to the same file

Just registered on this forum and could use some help please.I'm working on a program that out puts programming advice from a text file and then allows the user to input new advice for the next user replacing the old advice. I'm not having any problems writing to the file and replacing the old content. It's reading in the file I'm having issues with any help would be appreciated.

//allow users to input advice and displays it for the next user

#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>



int main()

{
using namespace std;
string advice;


ifstream adviceFile("advice.txt");

if(adviceFile.fail())
{
cout << "Input file failed to open.\n";
exit(1);
}

cout << adviceFile << endl;
adviceFile.close();

cout << "Enter some programming advice" << endl;
cout << "press enter twice when done.\n\n";

ofstream adviceFile("advice.txt");

if(getline(cin,advice))
{
adviceFile << advice;
}

adviceFile.close();

system("pause");

return 0;
}
1st: you define adviceFile as ifstream and then as ofstream. Your compiler should complain.
To mantain the same structure you have, I will call them iAdviceFile and oAdviceFile;

iAdviceFile is a ifstream.
It doesn't have a << operator. I guess you compiler complains where you write
cout << adviceFile << endl;
If you want to read the file you should use either the >> operator (or the getline) and then send it to the output.

something like (not sure about sintax, double-check it)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int main(void)
{

using namespace std;
string advice;
string theLine; //you might want to use the advice string already available
ifstream iAdviceFile("advice.txt");

if(adviceFile.fail())
{
cout << "Input file failed to open.\n";
exit(1);
}

while (!iAdviceFile.eof()) //show the content of the file
{
getline(iAdviceFile,theLine);
cout<<theLine<<endl;
}
adviceFile.close();
ofstream oAdviceFile("advice.txt");
//from here it looks like it is fine
//...
return 0;

}
Thank you very much for the help its working how it should now
If you think the answer is OK, mark it as solved!
Topic archived. No new replies allowed.