Qt程序读取文本只看到多行文件中的一行
Qt program to read text sees only one line in multi-line file
我编写了一个程序来读取文本文件中每行一个整数分数序列。该文件有一个需要跳过的标头。尽管盯着这个程序,但它只看到第一行(标题(,然后表现得好像在最后一样。
#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;
}
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何使代码打印文本文件中的第一行?
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 将字符串存储到文件下一行的变量中
- 为什么这个.c文件只有一行"../xx/xx.c"?
- 比较两个没有一行共同点的大文件
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 到达分隔符时跳到文本文件的下一行
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 从文本文件中随机选取一行
- 在获取从文件到矢量的每一行之后,数字将被更改或销毁
- 从文件中的一行读取特定数据-C++
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 为什么这一行不输出我的文本文件?
- 如何有效地从文件一行又一行地读取数据(相同类型)到多个向量(vectros的向量)
- 将文件一行的每个元素转换为整数
- 将文本文件一行一行地读入并行数组