QString和char *的相互转换
来源:互联网 发布:淘宝二手macbook pro 编辑:程序博客网 时间:2024/05/01 01:24
如何将QString转换为char *或者相反
How can I convert a QString to char* and vice versa ?(trolltech)
Answer:
Inorder to convert a QString to a char*, then you first need to get alatin1 representation of the string by calling toLatin1() on it whichwill return a QByteArray. Then call data() on the QByteArray to get apointer to the data stored in the byte array. See the documentation:
See the following example for a demonstration:
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QString str1 = "Test";
QByteArray ba = str1.toLatin1();
const char *c_str2 = ba.data();
printf("str2: %s", c_str2);
return app.exec();
}
Note that it is necessary to store the bytearray before you call data() on it, a call like the following
const char *c_str2 = str2.toLatin1().data();
will make the application crash as the QByteArray has not been stored and hence no longer exists.
To convert a char* to a QString you can use the QString constructor that takes a QLatin1String, e.g:
QString string = QString(QLatin1String(c_str2)) ;
以上转自:http://www.cppblog.com/Alina-zl/archive/2008/11/19/67323.html
1. 红色字体标出的存储那一步非常重要!!!!!!
2. 用toLatin1好像不支持中文,用toLocal8Bit可以支持。
- QString和char *的相互转换
- QString和char *的相互转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换 .
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- Qt中 QString 和int, char等的“相互”转换
- 终于20年后真正听完了Beyond的《大地》
- linus
- 如何删除MSN的共享文件夹
- Delphi面向对象:继承与封装
- java中Arraylist是干什么的?怎么用?
- QString和char *的相互转换
- 在Linux里设置环境变量的方法(export PATH)
- 系统变量与环境变量的关系
- 浅谈Delphi2009控件移植
- 如何:实现自定义成员资格用户
- 用SQL统计SQLServe表存储空间大小
- IT精英,必须掌握的命令行(very good, very practial)
- 高性能服务器的一些资源站点
- asp.net2.0学习历程-菜鸟到中级程序员的飞跃-.Net编程教程