I was trying to figure out why my size_t variables were returning -1 when using the find_first_of() function for agggesss when I realised the string that it was trying to search didn't actually contain anything. But I don't know where its contents are goign?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Open the file for reading and save into the string object
std::ifstream readFile("open.txt");
std::string fileContent;
if(!readFile.is_open()) {
std::cout << "Unable to read from file\n";
return 1;
}
else {
while(!readFile.eof()) {
getline(readFile, fileContent);
std::cout << fileContent << std::endl;
}
readFile.close();
}
/////////////////////////////////////////////////////////////
After this code however, I put a watch on 'fileContent' and it contains no value. I just can't see why. It's not going out of scope because the variable is created outside of the while loop. What's going on?
eof doesn't return true until you attempt to read past the end of the file. IE, if you're at the end of the file, it'll still return false until you read one more time.
Because of this, you're reading a blank line with getline(), which is what is erasing fileContent.
Ok thanks, I changed getline() to give a new variable 'fileContenetTemp' whatever is read, and then appended 'fileContent' with the value of 'fileContentTemp'. Works now.