QString作为Qt中内置的数据类型,功能强大且使用方便,绝对是在Qt开发过程中出场率最高的数据类型。本篇我们只重点探讨下QString转换成其他数据类型的注意事项。
short toShort(bool *ok=nullptr, int base=10) const;
ushort toUShort(bool *ok=nullptr, int base=10) const;
int toInt(bool *ok=nullptr, int base=10) const;
uint toUInt(bool *ok=nullptr, int base=10) const;
long toLong(bool *ok=nullptr, int base=10) const;
ulong toULong(bool *ok=nullptr, int base=10) const;
qlonglong toLongLong(bool *ok=nullptr, int base=10) const;
qulonglong toULongLong(bool *ok=nullptr, int base=10) const;
float toFloat(bool *ok=nullptr) const;
double toDouble(bool *ok=nullptr) const;
从上述方法可以看到,QString可以转换到几乎我们常用的基本数据类型,相比较势单力薄的atoi 函数来讲, 这个家族刀剑还是比较齐全的。所以,决定把这几把刀耍一下。
#include <QCoreApplication>
#include <QString>
#include <QDebug>
#include <iostream>
#include <stdio.h>
using namespace std;
#define string_expression(expression) #expression
#define string_to(string,type) QString(string).to##type()
#define compare_result(expression,dst_result) \
do{\
if( qAbs( (dst_result) - (expression)) < 0.0001f ) \
qDebug() << "[ pass ] " << expression << " == " << dst_result << "\t\t"<< string_expression(expression);\
else{ \
qDebug() << "[failed] " << expression << " != " << dst_result<< "\t\t" << string_expression(expression); \
}\
}while(0);
#define SHOW_HLINE(N) \
do{\
QString line = QString((N),QChar('_'));\
qDebug() << line;\
}while(0);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString test_string = "72";
compare_result(string_to(test_string,Short),72);
compare_result(string_to(test_string,UShort),72);
compare_result(string_to(test_string,Int),72);
compare_result(string_to(test_string,UInt),72);
compare_result(string_to(test_string,Float),72);
compare_result(string_to(test_string,Double),72);
SHOW_HLINE(100);
test_string = "72.890";
compare_result(string_to(test_string,Short),72);
compare_result(string_to(test_string,UShort),72);
compare_result(string_to(test_string,Int),72);
compare_result(string_to(test_string,UInt),72);
compare_result(string_to(test_string,Float),72.89);
compare_result(string_to(test_string,Double),72.89);
return a.exec();
}
看看结果:
[ pass ] 72 == 72 QString(test_string).toShort()
[ pass ] 72 == 72 QString(test_string).toUShort()
[ pass ] 72 == 72 QString(test_string).toInt()
[ pass ] 72 == 72 QString(test_string).toUInt()
[ pass ] 72 == 72 QString(test_string).toFloat()
[ pass ] 72 == 72 QString(test_string).toDouble()
"____________________________________________________________________________________________________"
[failed] 0 != 72 QString(test_string).toShort()
[failed] 0 != 72 QString(test_string).toUShort()
[failed] 0 != 72 QString(test_string).toInt()
[failed] 0 != 72 QString(test_string).toUInt()
[ pass ] 72.89 == 72.89 QString(test_string).toFloat()
[ pass ] 72.89 == 72.89 QString(test_string).toDouble()
what ? 当测试 字符串”72.890“转为整形变量的时候,结果居然是0 !不得不说太坑了
所以,郑重提示各位,QString 转整形,一定要慎重慎重再慎重(加大加粗描红)
具体为什么,下篇根据QString的源码进行分析