Reputation: 88397
I want to read a file line by line. Did something like
void Parse (string filepath) {
ifstream sourceFile;
sourceFile.open(filepath);
for (string line; getline(sourceFile, line);) {
cout << "1" << endl;
cout << line << endl;
}
}
int main() {
Parse("C:\\test.txt");
getchar();
return 0;
}
Then put some text into C:\test.txt
, but when I run, I dont get anything. Why? Not even the "1". I notice no exception if the file is not there too. I suppose that a sign of a problem?
Upvotes: 1
Views: 183
Reputation: 71009
I think you have problems opening the file. I would suggest two things:
if (sourceFile)
)EDIT: adding the actual solution to the problem in my answer(instead of just a comment) so that people won't miss it:
Here is one more thought - check the file name in its properties. Has happened to me that if windows hides the extension of the file the name is actually test.txt.txt, while what I see displayed is only test.txt.
Upvotes: 2
Reputation: 13661
change your for loop to
for (string line; sourceFile.good();) {
getline(sourceFile, line);
}
This way, you check the validity of your stream in the conditional part of the for, and get the line if the stream good.
Upvotes: 0
Reputation: 6999
You have to check for success/error manually. Try with ifstream::good()
:
sourceFile.open(filepath);
if(!sourceFile.good()) {
// do something
If you don't want to check manually, you can enable exceptions:
// call that before open()
sourceFile.exceptions ( ifstream::failbit | ifstream::badbit );
Upvotes: 3