在Qt中逐行读取文本文件

Was*_*RAR 37 c++ qt

如何在Qt中逐行读取文本文件?

我正在寻找相当于的Qt:

std::ifstream infile;
std::string line;
while (std::getline(infile, line))
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*gio 87

使用此代码:

QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
   QTextStream in(&inputFile);
   while (!in.atEnd())
   {
      QString line = in.readLine();
      ...
   }
   inputFile.close();
}
Run Code Online (Sandbox Code Playgroud)

  • @AlexanderMalakhov QIODevice ::文本是默认值. (3认同)
  • 模式不应该是 `(QIODevice::ReadOnly | QIODevice::Text)` 吗? (2认同)

LNJ*_*LNJ 6

这段代码可能更简单一点:

QFile inputFile(QString("/path/to/file"));
inputFile.open(QIODevice::ReadOnly);
if (!inputFile.isOpen())
    return;

QTextStream stream(&inputFile);
for (QString line = stream.readLine();
     !line.isNull();
     line = stream.readLine()) {
    /* process information */
};
Run Code Online (Sandbox Code Playgroud)

  • 您的代码片段很有帮助。`(!line.isNull())` 就是我所需要的。 (2认同)

R1t*_*chY 5

从 Qt 5.5 开始,您可以使用QTextStream::readLineInto. 它的行为类似于 ,std::getline并且可能更快QTextStream::readLine,因为它重用了字符串:

QIODevice* device;
QTextStream in(&device);

QString line;
while (in.readLineInto(&line)) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)