Important: Please read the Qt Code of Conduct -

Remove newline from QByteArray?

  • Hello,
    My task is to read a csv file into a struct.
    sample line:

    2017-03-12 07:50:01,17.7,1022.6,0.1,93.9

    The csv contains only doubles and the struct also (the date is irrelevant). The problem I have is that I cant read the last value because the csv contains a newline at the end of every line.

    struct Wstruct{
    	double tempIn;
            double press;
    	double tempOut;
    	double humi;
     Wstruct values;
    QByteArray line = file.readLine();
    values.tempIn = line.split(',').at(1).toDouble(); = line.split(',').at(2).toDouble();
    values.tempOut = line.split(',').at(3).toDouble();
    values.humi = line.split(',').at(4).toDouble();

    While the first three values work the last one is always zero.
    How can I remove the newline before assigning it to "values.humi"?
    I tried to use ".remove(QRegExp())" on "line" but this doesnt work because
    line is a QByteArray and not a QString.
    Any ideas?

  • Hi! You could use readLine():

    QFile file("in.csv");
    if (! | QIODevice::Text))
    QTextStream in(&file);
    while (!in.atEnd()) {
        const QString = in.readLine();
        // do something

  • Oh thanks!

    I found this works too:

    values.humi = QString(line.split(',').at(4)).remove(QRegExp("\\n")).toDouble();

    Is my approach also ok?

  • Yes, it's okay, too. Only keep in mind, that with readAll you'll create a copy of the whole file in RAM. Depending on the size of the file and your hardware, that might be a problem.

    Edit: Sorry, I think I didn't read your first post properly. You don't use readAll. My fault, forget it :-)

  • ok, thank you, the csv would not be longer than 300 lines anyway ;)

Log in to reply