在QT中使用QTextStream的readline读取文本文件时,默认不设置readline参数后从第二行读取,第一行内容不能正常显示

在QT中使用QTextStream的readline读取文本文件时,默认不设置readline参数后从第二行读取,第一行内容不能正常显示

问题描述:

1.问题如标题所描述的那样。
2.下面贴代码:

QFile file("d://wessontest.txt");
file.open(QIODevice::ReadOnly|QIODevice::Text);
QTextStream in(&file);
Student stu;     //Student自定义类型,包含姓名,学号,成绩,排名四个成员
while(!in.atEnd())
{
     in.readLine();
         in>>stu.name>>stu.sno>>stu.score>>stu.ranking;
         qDebug()<<stu.name<<" "<<stu.sno<<" "<<stu.score<<" "<<stu.ranking;
        }

结果如下:
图片说明

第一行数据是缺失的。

后来我在网上参考了关于按行读取的代码,例子如下:

    while (!in.atEnd())
    {
    QString line = in.readLine();
    qDebug()<<line;
    }

这种情况下能够正常读取所有结果。

不太能够理解为什么我将文件流读取到对象中会出错,直接按照string输出就没错。

后来偶然将第一种情形中的in.readline()里面的参数设置为-1,竟然得到了正常的结果。即:

while(!in.atEnd())
{
     in.readLine(-1);
         in>>stu.name>>stu.sno>>stu.score>>stu.ranking;
         qDebug()<<stu.name<<" "<<stu.sno<<" "<<stu.score<<" "<<stu.ranking;
        }

图片说明

拜托各位大神!!!

第一次执行in.readLine()后,光标定位在第二行的开头
第一次执行in>>stu.name后(将第二行的数据填充Student),光标定位在第二行结尾
第二次执行in.readLine()后(读取的内容为空),光标定位在第三行的开头
第二次执行in>>stu.name后(将第三行的数据填充Student),光标定位在第三行结尾

Student stu;
while (!in.atEnd()) {
    QString line = in.readLine();
    qDebug() << "test: " << line;
    in >> stu.name >> stu.sno >> stu.score >> stu.ranking;
    qDebug() << stu.name << stu.sno << stu.score << stu.ranking;
}

输出:
test:  "Wesson 201930344107 100 1"
"Jim" "201930344108" 98 2
test:  ""
"Alex" "201930344109" 97 3
test:  ""
"John" "201930344110" 96 4