问题
I have a problem reading file, opened with fstream on windows.
std::ifstream file(file_name);
if(!file.is_open()){
std::cerr << "file cannot be opened";
}
if (!file){
std::cerr << "errors in file";
}
std::vector<std::string> strings;
std::string str;
while (std::getline(file, str)) {
strings.push_back(str);
}
File opened sucessfully and it has no errors, but cycle with getline gets no content.
Besides this sample runs perfect and prints whole file content
std::copy(std::istream_iterator<std::string>(file), std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cerr, "\n"));
On linux everything is perfect, same file, same code, getline in cycle reads all.
Visual Studio 2013
Edit:
I forgot to mention that i have this little line of code before cycle with getline
std::cout << file.rdbuf();
On linux this line just prints file content, on windows it not only print, but makes file inacessible to std::getline
回答1:
getline()
extracts characters from the input stream until either newline character is reached or delim
which is also a character, but instead of only extracting, getline discards the deliminating character. Check your file to see if you started with a newline character
, meaning in the file you started on a line other than the first one. If so,
while (std::getline(file, str)) {
strings.push_back(str);
}
would always iterate only 1 time
, returning no characters because it only discarded the newline character.
while (std::getline(file, str) || !file.eof) {
strings.push_back(str);
}
Will now, if it runs into a deliminating character
, also check if the end of the file has been reached.
回答2:
The problem was in calling
std::cout << file.rdbuf();
before while(std::getline)
on Windows this line makes file not accessible to std::getline
来源:https://stackoverflow.com/questions/40307840/reading-file-content-opened-with-ifstream