Reputation: 475
I am having trouble with split function on QT. I have a text file and the very first line is like this:
10,100;100,100;100,100;100,200;100,200;300,200;300,200;300,350;300,350;250,350;250,350;250,300;250,300;200,300;200,300;200,400;200,400;10,400;10,400;10,100
Here every two numbers represents a point with x an y values and semicolons divides the points. After every semicolon there is a new point.
What I want to do is split these numbers element by element like;
Element 0: 10
Element 1: 100
Element 2: 100
Element 3: 100
...
I have managed to do this but there wasn't any semicolons or colons in the text file.
First line of the text file:
10 100 100 100 100 200 300 200 300 350 250 350 250 300 200 300 200 400 10 400 10 100
This is how i did it:
void Dialog::readFile()
{
QFile file("/Path/of/the/text/file/Data.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "info", file.errorString());
}
QString line = file.readLine();
qDebug() << "line:" << line << "\n";
QStringList list = line.split(" ");
double element;
for(int i = 0; i < list.size(); i++) {
element = list.at(i).toDouble();
points_.append(element);
qDebug() << "element:" << element << "\n";
}
}
Output of this code is:
line: "10 100 100 100 100 200 300 200 300 350 250 350 250 300 200 300 200 400 10 400 10 100\r"
element: 10
element: 100
element: 100
element: 100
element: 100
element: 200
element: 300
element: 200
....
I want to do this exactly the same way. Is there any suggestion?
PS: I am new on QT so please consider this.
Upvotes: 0
Views: 1125
Reputation: 19627
You can use regular expression with the QString::split
overload taking QRegExp
or the next one taking QRegularExpression
:
QStringList list = line.split(QRegExp(",|;")); // ",|;" matches ',' or ';'
QRegExp
is called to be deprecated, but it can do the job here.
Upvotes: 1