gpt4 book ai didi

c++ - 读取使用 ifstream 打开的文件内容

转载 作者:行者123 更新时间:2023-11-27 23:59:27 24 4
gpt4 key购买 nike

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

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循环没有内容。

此外,此示例运行完美并打印了整个文件内容

std::copy(std::istream_iterator<std::string>(file), std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cerr, "\n"));

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

Visual Studio 2013

编辑:

我忘了说我在使用 getline 循环之前有这一行代码

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

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

最佳答案

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

while (std::getline(file, str)) {
strings.push_back(str);
}

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

while (std::getline(file, str) || !file.eof) {
strings.push_back(str);
}

现在,如果遇到分隔符,还会检查是否已到达文件末尾。

关于c++ - 读取使用 ifstream 打开的文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40307840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com