【问题标题】:Qt program to read text sees only one line in multi-line fileQt程序读取文本在多行文件中只看到一行
【发布时间】:2017-11-16 18:37:04
【问题描述】:

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

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

这里是scores.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

【问题讨论】:

    标签: c++ qt qt5 qtextstream


    【解决方案1】:

    当你使用 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;
    }
    

    【讨论】:

    • 谢谢我从你的第一句话中找到了错误,但似乎修复可以只是用 ts.atEnd() 替换 qFile.atEnd()。
    猜你喜欢
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多