Why did you comment out line 23? Seems like lines 32 and 33 are backwards. You should test if it's open, then if it's open, close it. And it never hurts to clear the bits too.
I'm sure this is overkill, but I imagine it'll work. Experiment around.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;ofstream thefile;
thefile.open ("example.txt");
thefile <<"writing this to a file. \n";
thefile.close();
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof())
{
getline (myfile, line);
cout << line << endl;
}
myfile.close();
}
else cout << "unable to open file";
cout<<line;
cin>>line;//used only for a makeshift pause here
if (myfile.is_open())
{
myfile.close();
}
myfile.clear();
myfile.open ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof())
{
getline (myfile, line);
cout << line << endl;
}
myfile.close();
}
else cout << "unable to open file";
return 0;
} You can never have too many "clear" statements, though often they're compeletely useless. Anyway, give it a shot. Experiment.