1

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

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

这是 score.txt 的内容:

just test data
69
48
38
2
5
1
1
4

这是程序的输出

"just test data"
found  0  lines

你能看出为什么程序看不到 8 行分数吗?我在带有 Mingw32 的 Windows 上使用 Qt 5.3.1

4

1 回答 1

2

当您使用 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;
}
于 2017-11-16T18:50:01.420 回答