Qt文件无法完整读取

本来想要依次读取文件数据

 while(!file.atEnd())
     {  out>>name;
       out>>team;
       out>>three;addall.Three+=three;
       out>>board;addall.Board+=board;
       out>>dunk; addall.Dunk+=dunk;
       out>>steal;addall.Steal+=steal;
       out>>score;addall.Score+=score;
       out>>date;
      qDebug()<<three;
      }

img


这是文件存储的内容
可结果只读取了一组数据就结束了

img


如图,正确结果应是6
Qt、C++相关

【以下回答由 GPT 生成】

问题的根本原因是文件中的数据并未按照out的读取方式写入。根据代码,可以看出你是用out对象来读取文件,但是在代码中并没有显示出out对象是如何读取文件的。假设你使用的是QFile来读取文件,那么可以修改代码如下:

QFile file("yourFilePath");
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    QTextStream in(&file);

    while(!in.atEnd()) {  
        QString name;
        QString team;
        int three;
        int board;
        int dunk;
        int steal;
        int score;
        QString date;

        in >> name >> team >> three >> board >> dunk >> steal >> score >> date;
        qDebug() << name << team << three << board << dunk << steal << score << date;
    }

    file.close();
} else {
    qDebug() << "Failed to open file";
}

这里使用了QFileQTextStream来读取文件内容。具体步骤如下:

  1. 创建QFile对象,并指定要读取的文件路径。

cpp QFile file("yourFilePath");

  1. 打开文件,并指定读取模式。

cpp if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { // 文件打开成功的处理逻辑 } else { // 文件打开失败的处理逻辑 }

  1. 创建QTextStream对象,并将其关联到QFile对象以进行读取操作。

cpp QTextStream in(&file);

  1. 使用QTextStream的输入操作符>>按照预期的数据类型读取文件内容,并将读取到的数据存储到相应的变量中。

cpp in >> name >> team >> three >> board >> dunk >> steal >> score >> date;

  1. 处理读取到的数据。

  2. 关闭文件。

cpp file.close();

这样修改后的代码应该能够正确读取文件内容,并输出6组数据。如果问题仍然存在,请检查文件路径和文件内容是否正确。如果问题依然存在,请提供更多的细节信息,以便进一步排查问题。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^