Qt程序读取文本只看到多行文件中的一行

Qt program to read text sees only one line in multi-line file

本文关键字:文件 一行 读取 程序 取文本 Qt      更新时间:2023-10-16

我编写了一个程序来读取文本文件中每行一个整数分数序列。该文件有一个需要跳过的标头。尽管盯着这个程序,但它只看到第一行(标题(,然后表现得好像在最后一样。

#include <QCoreApplication>
#include <QString>
#include <QTextStream>
#include <QDebug>
#include <QFile>
bool readScores(QString path)
{
  int line_count = 0;
  QFile qFile(path);
  if(!qFile.exists())
    {
      qDebug()<<"path does not exist:" << path;
      return false;
    }
  if(!qFile.open(QIODevice::ReadOnly|QIODevice::Text)){
      qDebug("open fails");
      return false;
    }
  QTextStream ts(&qFile);
  qDebug()<<ts.readLine();// just read the head...
  while(!qFile.atEnd())
    {
      line_count++;
      int score;
      QTextStream tsLine;
      QString line = ts.readLine(512);
      tsLine.setString(&line);
      tsLine >> score;
      qDebug()<<"Just read"<<score;
    }
  qDebug()<<"found "<<line_count<<" lines";
  qFile.close();
  return true;
}
int main(int argc, char *argv[])
{
  QCoreApplication a(argc, argv);
  readScores("e:/tmp/scores.txt");
  return a.exec();
}

这是分数的内容.txt:

just test data
69
48
38
2
5
1
1
4

这是程序的输出

"just test data"
found  0  lines

你能明白为什么程序看不到 8 行分数吗?我在Windows上使用Qt 5.3.1和Mingw32

当你使用

QTextStream 时,你不应该再使用 QFile:

bool readScores(QString path)
{
    [...]
    QTextStream ts(&qFile);
    qDebug()<<ts.readLine();// just read the head...
    QString line;
    do
    {
        line = ts.readLine();
        bool ok;
        int score = line.toInt(&ok);
        if(ok){
            qDebug()<<"Just read"<<score;
            line_count++;
        }
    }
    while (!line.isNull());
    qDebug()<<"found "<<line_count<<" lines";
    qFile.close();
    return true;
}