gpt4 book ai didi

c++ - QFile忽略最后一个换行符

转载 作者:太空宇宙 更新时间:2023-11-04 13:14:00 25 4
gpt4 key购买 nike

我正在使用 Qt 读取文件

  std::vector<QString> text;

QFile f(file);
if (f.open(QFile::ReadWrite | QFile::Text) == false)
throw my_exception();

QTextStream in(&f);
QString line;
while(!in.atEnd()) {
line = in.readLine();

text.push_back(line);
}
f.close();

这种方法的问题是:我无法读取文件末尾的额外换行符。

假设我有以下文本文件

Hello world\r\n
\r\n

我无法为最后的 \r\n 行获取空字符串。我该如何解决这个问题?

最佳答案

根据 http://doc.qt.io/qt-4.8/qtextstream.html#readLine\r\n 总是被修剪。所以你会在每一行阅读中错过它们。你可以:

a) 在使用 readLine()

后向读取的字符串添加行终止符

b) 使用QFiles.readLine() 读入一个QByteArray,它不接触读取的字节:

while (!f.atEnd()) {
QByteArray line = f.readLine();
process_line(line);
}

c) 使用另一种方法读取文件,例如std::istream。参见 http://www.cplusplus.com/reference/istream/istream/getline/对于等效的 getline

关于c++ - QFile忽略最后一个换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38348153/

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