gpt4 book ai didi

QT无法写入unicode文件unicode字符串

转载 作者:行者123 更新时间:2023-12-04 18:15:31 25 4
gpt4 key购买 nike

我正在使用QT Creator,创建了控制台应用程序。一切都是最新的。操作系统是Windows XP。

我创建了一个保存一些匈牙利字符的QString。大多数匈牙利字符不需要unicode,但是带有双斜杠的重音字符需要unicode。

我尝试将QString内容写入文件,但我的Unicode字符在文件中丢失了重音。换句话说,unicode信息会一直丢失。

我的代码在下面。

#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
#include <QDate>
#include <QFile>
using namespace std;


int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);

QString szqLine = "NON-UnicodeIsOK: áéüúöóí NEED-Unicode: űő";
//These are Hungarian chars and require unicode. Actually, only the u & o, each having double
//slashes for eccents require unicode encoding.

//Open file for writing unicode chars to.
QFile file("out.txt");
if ( !file.open(QIODevice::WriteOnly | QIODevice::Text) ){
return 1;
}

//Stream the QString text to the file.
QTextStream out(&file);
out.setCodec("UTF-8");

out << szqLine << endl; //Use endl for flush. Does not properly write ű and ő chars.
//Accents missing in file.

file.close(); //Done with file.

return app.exec();
}

最佳答案

  • 文件的编码是什么?至少在跨平台工作时,在源文件中使用非ascii编码通常会引起问题。我认为MSVC在那里存在一些问题。
  • QString foo =“unicode字符串”使用从ascii到unicode的隐式转换,这也会引起问题。始终明确指定文字使用的编码方式,例如通过使用QLatin1String()包装文字,如果它是latin1:

    QString foo = QLatin1String(“some latin1 string”);

  • 或utf-8(根据您的情况),QString::fromUtf8():
    QString foo = QString::fromUtf8( "funny characters" );
  • 在将字符串写入文件(虽然代码看起来正确,这是可能出现错误的另一个来源)之前,请检查qt小部件(例如QLineEdit)是否正确显示了它。

  • 为了避免此类错误,我更喜欢使用英文字符串将源文件保留为纯ascii格式,然后使用Qt的国际化工具对其进行翻译。

    编辑:另请参阅 this question about UTF-8 literals in MSVC 2008的可接受答案。

    关于QT无法写入unicode文件unicode字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4300612/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com