Basically I open the text file (test.txt) and that contains a few words only and the first time it is opened and read line by line it works. I then seekg() to the first line (0) and then try to repeat but adding to a dynamic string array..
It doesnt do this but instead it follows the program process down to the end. No Errors, nothing.
#include <iostream>
#include <fstream>
#include <string>
#include <new>
int main() {
usingnamespace std;
string tmpline, filename;
int i = 0;
cout << "Enter file name: ";
getline(cin, filename);
ifstream file(filename.c_str());
if (file.is_open()) {
while (! file.eof()) {
getline(file, tmpline);
//cout << tmpline << endl
i++;
}
cout << "File contains: " << i << " Lines." << endl;
file.seekg(0);
string * lines;
lines = new (nothrow) string[i];
int n = 0;
while (! file.eof()) {
getline(file, lines[n]);
n++;
}
file.close();
for (int d = 0; n > d; d++) {
cout << lines[n] << endl;
}
delete[] lines;
} else {
cout << "Unable to open file" << endl;
}
int grab; // just so i can tap 0 and it exit
cin >> grab; // so i could read the screen..
return(0);
}
I hope someone can help, or tell me how to be more efficent too..
I also encountered this kind of problems before. Then I tried to read the fstream and find this clear() functions, I used it in my program and problems solved.
To use file.clear() is the right way to solve such problems. It seems fstream will set some flags, which caused some problems. Use clear() can reset them all.