0
Why doesn't this code work?
#include <iostream> #include <fstream> using namespace std; int main () { fstream MyFile("test.txt", ios::out | ios::in); MyFile << "This is awesome! \n"; string line; while ( getline (MyFile, line) ) { cout << line << '\n'; } MyFile.close(); }
2 Answers
+ 2
I suppose, you are trying to read from current position in file, because file was not closed. And current position is end of file. You need to rewind current position at begin of the file.
try to use:
MyFile.clear(); //clear eof flag
MyFile.seekg(0); // move current position to begin of the file
ps. also you have not included <string>
+ 1
A have just checked if the file is opened - false