本文介绍了读取用 ifstream 打开的文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读取文件时遇到问题,在 Windows 上使用 fstream 打开.

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);
}

文件打开成功并且没有错误,但是使用 getline 循环没有内容.

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"));

在 linux 上一切都很完美,相同的文件,相同的代码,循环中的 getline 读取所有内容.

On linux everything is perfect, same file, same code, getline in cycle reads all.

Visual Studio 2013

Visual Studio 2013

我忘了提到我在用 getline 循环之前有这小行代码

I forgot to mention that i have this little line of code before cycle with getline

std::cout << file.rdbuf();

在 linux 上这行只打印文件内容,在 windows 上它不仅打印,而且使 std::getline

On linux this line just prints file content, on windows it not only print, but makes file inacessible to std::getline

推荐答案

getline() 从输入流中提取字符,直到到达换行符或 delim也是一个字符,但不仅仅是提取,getline 会丢弃分隔字符.检查您的文件以查看您是否以 换行符 开头,这意味着在文件中您不是从第一个行开始的.如果是这样,

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);
}

总是只迭代1次,不返回任何字符,因为它只丢弃了换行符.

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.

这篇关于读取用 ifstream 打开的文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 05:54