QString和string互转中文字符

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值