Question

I have a struct point

struct Point
{
    double x;
    double y;
    double z;
}

And want to convert it to a QString "(value of x, value of y, value of z)" and convert it back? Any easy way? What I figured out for the forward conversion is

QString PointToString( const Point& pt )
{
     return QString("(%1, %2, %3)").arg(pt.x).arg(pt.y).arg(pt.z);
}

And I cannot figure out how to convert it back.

Point StringToPoint( const QString& s )
{
     // How?
}

Thanks.

Was it helpful?

Solution

Use regular expressions:

QString s = "(2, 5.3, 1e8)";
QRegExp regexp("\\(([^,]+), ([^,]+), ([^)]+)\\)");
if (regexp.exactMatch(s)) {
  double x = regexp.capturedTexts()[1].toDouble();
  double y = regexp.capturedTexts()[2].toDouble();
  double z = regexp.capturedTexts()[3].toDouble();
  qDebug() << x << y << z;
}

Output: 2 5.3 1e+08

Be aware that arg can produce a number representation with comma separator (e.g. '3,14') on systems with certain locales. Parsing this representation would be problematic. So you should use QLocale::c().toString(number) to perform system independent conversion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top