分享

QString和string互转中文字符

 italyfiori 2013-08-07

string -> QString

1 std::string strStd = "中文字符";
2 QString strQ = QString::fromLocal8Bit(strStd.c_str());

QString -> string

1 QString strQ("中文字符");
2 std::string strStd= strQ.toStdString();
3 QTextCodec *code = QTextCodec::codecForName("gb18030");
4  // 如果code为0,表示在运行的机器上没有装gb18030字符集。不过一般的中文windows系统中都安装了这一字符集
5  if (code) strStd= code->fromUnicode(strQ).data();

或者用如下方式:
 
QString s2q(const string &s)   
{   
        return QString(QString::fromLocal8Bit(s.c_str()));   
}   
string q2s(const QString &s)   
{   
        return string((const char *)s.toLocal8Bit());   
}  

 

 

C/C 中读取中文路径文件的方法

有时候用ifstream或ofstream打开带有中文路径的文件会失败。

解决办法:
1、使用C语言的函数设置为中文运行环境
setlocale(LC_ALL,"Chinese-simplified");

2、使用STL函数设置为系统语言环境
std::locale::global(std::locale(""));

当然选2啦!

 

 

 

1.最近编程采用C 文件操作来读入一个文件,代码:

                ifstream inf;

                inf.open(strpath);     //通过文件路径打开文件

                当文件路径strpath中带有中文时程序运行错误,导致卡死,后来终于弄清用C 方法打开带中文路径的文件时会有BUG,谁叫这东东是老外写的呢,但是通过下面的方法可以解决,如代码:

               ifstream inf;                              //C 方式打开文件
               locale::global(locale(""));         //将全局区域设为操作系统默认区域
               inf.open(strpath);                    //通过文件路径打开文件
               locale::global(locale("C"));     //还原全局区域设定string -> QString

1 std::string strStd = "中文字符";
2 QString strQ = QString::fromLocal8Bit(strStd.c_str());

QString -> string

1 QString strQ("中文字符");
2 std::string strStd= strQ.toStdString();
3 QTextCodec *code = QTextCodec::codecForName("gb18030");
4  // 如果code为0,表示在运行的机器上没有装gb18030字符集。不过一般的中文windows系统中都安装了这一字符集
5  if (code) strStd= code->fromUnicode(strQ).data();

或者用如下方式:
 
QString s2q(const string &s)   
{   
        return QString(QString::fromLocal8Bit(s.c_str()));   
}   
string q2s(const QString &s)   
{   
        return string((const char *)s.toLocal8Bit());   
}  

 

 

C/C 中读取中文路径文件的方法

有时候用ifstream或ofstream打开带有中文路径的文件会失败。

解决办法:
1、使用C语言的函数设置为中文运行环境
setlocale(LC_ALL,"Chinese-simplified");

2、使用STL函数设置为系统语言环境
std::locale::global(std::locale(""));

当然选2啦!

 

 

 

1.最近编程采用C 文件操作来读入一个文件,代码:

                ifstream inf;

                inf.open(strpath);     //通过文件路径打开文件

                当文件路径strpath中带有中文时程序运行错误,导致卡死,后来终于弄清用C 方法打开带中文路径的文件时会有BUG,谁叫这东东是老外写的呢,但是通过下面的方法可以解决,如代码:

               ifstream inf;                              //C 方式打开文件
               locale::global(locale(""));         //将全局区域设为操作系统默认区域
               inf.open(strpath);                    //通过文件路径打开文件
               locale::global(locale("C"));     //还原全局区域设定

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多