QString与String转换,中文乱码解决方法

首先确保源文件为UTF-8编码

我用的VS自带的高级保存选项修改,适合项目文件不多的。可以使用一些扩展,但我没学会
点击 工具-自定义,在命令里添加“高级保存选项”
在这里插入图片描述
接着一个个打开文件,点击 文件-高级保存选项,选择“UTF-8无签名”,再保存文件就行
尽量将项目属性-高级-字符集,也改成使用 Unicode 字符集

QString转String相互转换

1.代码里中文字符串,控件显示正常,读取文件正常

string Path= "G:/广州_20240620.bin";
//String转QString
QString qstr=QString::fromStdString(Path);	//正常
//QString转String
string str=qstr.toStdString();	//正常

//linedit控件显示正常
ui.lineEdit->setText(QString::fromStdString(Path));

//读文件正常
FILE* file;
int openFail = fopen_s(&file, Path.c_str(), "rb");
if (openFail)
	return;

2.另一种情况,QXmlStreamReader读取xml
使用toStdString时,控件显示正常,但是读文件失败。
感觉像是QString->乱码,乱码->Qstring,所以显示正常。

//读取xml时,VS调试器会中文乱码,添加监视后在变量名后加上,s8,看着也正常.
QString qstr= reader.readElementText().toStdString();
string Path=qstr.toStdString();
//测试
qDebug() << qstr;	//正常
qDebug() << Path.c_str();	//正常
cout<< Path;	//乱码

//写入xml也正常
writer.writeTextElement("Path", QString::fromStdString(Path));

//此时linedit控件也显示正常
ui.lineEdit->setText(QString::fromStdString(Path));

//但是读文件会失败
FILE* file;
int openFail = fopen_s(&file, Path.c_str(), "rb");
if (openFail)
	return;

此时使用另一种麻烦点的转换方式toLocal8Bit,控件显示正常,读文件正常。
但是有一个问题,就是你用它转换代码里的中文字符串就会乱码!!!个人感觉还没研究透彻…

//读取xml时,VS调试器正常显示
QString qstr= reader.readElementText().toStdString();
string Path= qstr.toLocal8Bit().data();//或者 qstr.toLocal8Bit().toStdString();
//测试
qDebug() << qstr;	//正常
qDebug() << Path.c_str();	//乱码
cout<< Path;	//正常

//写入xml正常
writer.writeTextElement("Path", QString::fromLocal8Bit(Path.c_str()));

//linedit控件显示正常
ui.lineEdit->setText(QString::fromLocal8Bit(Path.c_str()));

//读文件正常
FILE* file;
int openFail = fopen_s(&file, Path.c_str(), "rb");
if (openFail)
	return;
	
//===================================================

string Path= "G:/广州_20240620.bin";
//String转QString
QString qstr=QString::fromLocal8Bit(Path.c_str());	//乱码,linedit更不用说了
//QString转String
string str=qstr.toLocal8Bit().data();	//乱码

参考链接:
https://blog.csdn.net/m0_59023203/article/details/134937063
https://www.cnblogs.com/lqshang/p/17298205.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值