Here's how you'd do it with proper error checking.
Since it's a text file, you'd set a QTextStream
on it, and read it line-by-line. You immediately split
the line on the colon separator, and check if you've got three pieces. It is not necessary to check for an empty line
, since split
can handle empty strings, as well as strings with no separators.
If you got three pieces, parse the last piece to an integer and check if it succeeded. If it did, you can call your method, passing it the first two pieces with whitespace (if any) trimmed, and the integer you parsed.
You most likely want whitespace trimming, so that the behavior for the string parts is the same as for the integer part: toInt
ignores whitespace, after all.
Output:
read "a1" "b1" 10
read "Lol" "cats" 33
// https://github.com/KubaO/stackoverflown/tree/master/questions/simple-parse-37902620
#include <QtCore>
void callMethod(const QString & a, const QString & b, int c) {
qDebug() << "read" << a << b << c;
}
void parse(QIODevice * input)
{
QTextStream in(input);
while (!in.atEnd()) {
auto const line = in.readLine();
auto const parts = line.split(':');
if (parts.size() == 3) {
bool ok;
auto p3 = parts.at(2).toInt(&ok);
if (ok)
callMethod(parts.at(0).trimmed(), parts.at(1).trimmed(), p3);
}
}
}
int main(int argc, char ** argv) {
QCoreApplication app{argc, argv};
QByteArray data{" a1 : b1 : 10 \nLol:cats: 33"};
QBuffer buf(&data);
if (buf.open(QIODevice::ReadOnly))
parse(&buf);
}