C++常用类型转换

1.QString转string

QString  qstr = "test";
string s = qstr.toStdString();

2.string转QString

string s = "test";
QString qstr = QString::fromStdString(s);

3.QString转char *

方法1(推荐):

QString  qstr = "test"; 
char * filename = qstr.toUtf8().data();

方法2:

QString  qstr = "test"; 
char * filename = qst.toLocal8Bit().data();

4.char *转QString

char *ch="test";
QString str(ch);   // Qt5     
QString str = QString::fromUtf8(ch));    //  Qt4

5.QString转const char *

方法1:

QString  qstr = "test"; 
char* filename = qstr .toStdString().c_str();

6.float转string

stringstream ss;
float b = 10.1;
ss << b;
string p;
ss >> p;
cout << p;

注意:如果需要多个float转成string,stringstream的变量ss貌似无法共用,例如下面的例子中只有thresh1能成功输出。thresh2和thresh3是空的。

stringstream ss;
float thresh1 = 10.1, thresh2 = 20.1, thresh3 = 30.1;
string p1, p2, p3;
ss << thresh1;
ss >> p1; cout << p1;
ss << thresh21;
ss >> p2; cout << p2;
ss << thresh3;
ss >> p3; cout << p3;

如果需要多个float转成string,可以用多个stringstream变量,如下:

stringstream ss1, ss2, ss3;
float thresh1 = 10.1, thresh2 = 20.1, thresh3 = 30.1;
string p1, p2, p3;
ss1 << thresh1;
ss1 >> p1; cout << p1;
ss2 << thresh21;
ss2 >> p2; cout << p2;
ss3 << thresh3;
ss3 >> p3; cout << p3;

方法2:借助float转QString,再QString转string

7.float转QString

float thresh1 = 10.1, thresh2 = 20.1, thresh3 = 30.1;
QString  qstr = QString("%1+%2 %3").arg(thresh1).arg(thresh2).arg(thresh3); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值