QTextStream::readLine(): invalid return value

495 views Asked by At

I'm trying to read from a file using this code:

const char *imageFile = repertoire_Hu.filePath(img_files_Hu[i]).toStdString().c_str();
QFile f(imageFile);
QTextStream out(&f);
float tab2[7];
int q = 0;
if(f.open(QIODevice::ReadOnly | QIODevice::Text))
{
    while(!out.atEnd())
    {
        QString line = out.readLine();
        tab2[q] = line.toFloat();
        q ++;
    }
}
f.close();

This is the content of my file


-1557.35

0.659662

-2.65505

5.43287e-23

5.4945e-34

-5.65088e-35

-1.35751e+38

But when I plot the values after reading the file I get wrong values (completely different from the values in the file when I compare them) and sometimes the file can't be opened and most of the time it doesn't read all the values in the file.

I guess I'm doing something wrong somewhere but I can't figure it.

2

There are 2 answers

1
hyde On

I don't spot anything immediately wrong, so you need to do more debugging. This should help you find the problem:

while(!out.atEnd())
{
    QString line = out.readLine();
    bool ok = false;
    qDebug() << "Line index" << q << "contents:" << line;        
    float value = line.toFloat(&ok);
    if (ok) {
        qDebug() << "Parsing succeeded:" << tab2[q];
        tab2[q] = value;
        ++q;
    } else {
        qDebug() << "Parsing failed, skipping line!";
        // or break, or whatever you want to do
    }
}
2
László Papp On

Make sure you do not have empty lines in-between, nor any unwished white spaces at the end of the lines. After a copy/paste from your data file, it seems you have that all around.

This works perfectly fine for me:

data.txt

-1557.35
0.659662
-2.65505
5.43287e-23
5.4945e-34
-5.65088e-35
-1.35751e+38

main.cpp

#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QString>
#include <QtCore/QDebug>

int main()
{

    QFile f("data.txt");
    QTextStream out(&f);
    float tab2[7];
    int q = 0;
    if(f.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        while(!out.atEnd())
        {
            QString line = out.readLine();
            tab2[q] = line.toFloat();
            qDebug() << "LINE:" << tab2[q];
            q ++;
        }
    }
    f.close();

    return 0;
}

Output

g++ -Wall -fPIC -I/usr/include/qt/QtCore -I/usr/include -I/usr/include/qt -lQt5Core main.cpp && ./a.out

LINE: "-1557.35"                                                                                     LINE: "0.659662"                                                                                 
LINE: "-2.65505"                                                                                 
LINE: "5.43287e-23"                                                                              
LINE: "5.4945e-34"                                                                               
LINE: "-5.65088e-35"                                                                             
LINE: "-1.35751e+38"