GrahamB
5th June 2016, 09:52
I have discovered something with a ternary statement that I don't quite understand.
If I use a normal if - else construct I have no problem in compiling, however using the same variables in a ternary statement I get a Invalid conversion from int to constant char* error.
Here is my code:
Header file
#ifndef TERNARYTEST_H
#define TERNARYTEST_H
#include <QString>
#include <QDebug>
#include <QRegExp>
typedef QMap<QString, QVariant> MyMap;
void setup(void);
bool isInt(QString);
#endif // TERNARYTEST_H
and the main file
#include <QCoreApplication>
#include <ternaryTest.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
setup();
return a.exec();
}
void setup()
{
MyMap map;
QString str = "Release Time: 2000";
QString val;
QString key;
bool ok;
val = (str.section(':',1,-1)).trimmed();
key = (str.section(':',0,0)).toUpper().trimmed();
qDebug()<<val;
qDebug()<<key;
if ( isInt(val) )
map[key] = val.toInt();
else
map[key] = val;
qDebug()<<map;
map[key] = isInt(val) ? val.toInt(&ok, 10) : val; /// Error compiling here
exit(0);
}
bool isInt(QString s)
{
QRegExp re("\\d*");
return re.exactMatch(s);
}
As the if - else constructs works fine I have no problem. Just curious as to the compiler error on the ternary statement.
The object of the program is to use everything before the first occurrence of a colon as a key in a QMap and everything after, including any colons as a QVariant value (Int or QString).
Thanks in advance.
Regards
Graham Benney
If I use a normal if - else construct I have no problem in compiling, however using the same variables in a ternary statement I get a Invalid conversion from int to constant char* error.
Here is my code:
Header file
#ifndef TERNARYTEST_H
#define TERNARYTEST_H
#include <QString>
#include <QDebug>
#include <QRegExp>
typedef QMap<QString, QVariant> MyMap;
void setup(void);
bool isInt(QString);
#endif // TERNARYTEST_H
and the main file
#include <QCoreApplication>
#include <ternaryTest.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
setup();
return a.exec();
}
void setup()
{
MyMap map;
QString str = "Release Time: 2000";
QString val;
QString key;
bool ok;
val = (str.section(':',1,-1)).trimmed();
key = (str.section(':',0,0)).toUpper().trimmed();
qDebug()<<val;
qDebug()<<key;
if ( isInt(val) )
map[key] = val.toInt();
else
map[key] = val;
qDebug()<<map;
map[key] = isInt(val) ? val.toInt(&ok, 10) : val; /// Error compiling here
exit(0);
}
bool isInt(QString s)
{
QRegExp re("\\d*");
return re.exactMatch(s);
}
As the if - else constructs works fine I have no problem. Just curious as to the compiler error on the ternary statement.
The object of the program is to use everything before the first occurrence of a colon as a key in a QMap and everything after, including any colons as a QVariant value (Int or QString).
Thanks in advance.
Regards
Graham Benney