Remove newline from QByteArray?
-
wrote on 12 Mar 2017, 08:50 last edited by A Former User 3 Dec 2017, 08:57
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; }; ... private: Wstruct values; ... QByteArray line = file.readLine(); values.tempIn = line.split(',').at(1).toDouble(); values.press = 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? -
wrote on 12 Mar 2017, 09:02 last edited by A Former User 3 Dec 2017, 09:20
Hi! You could use readLine():
QFile file("in.csv"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream in(&file); while (!in.atEnd()) { const QString = in.readLine(); // do something }
-
wrote on 12 Mar 2017, 09:06 last edited by pauledd 3 Dec 2017, 09:06
Oh thanks!
I found this works too:
values.humi = QString(line.split(',').at(4)).remove(QRegExp("\\n")).toDouble();
Is my approach also ok?
-
wrote on 12 Mar 2017, 09:09 last edited by A Former User 3 Dec 2017, 09:12
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 :-)
-
wrote on 12 Mar 2017, 09:16 last edited by
ok, thank you, the csv would not be longer than 300 lines anyway ;)
5/5