Alex
Alex

Reputation: 1031

Qt utf-8 encoding issue

    #include <iostream>

    #include <QString>

    using namespace std;
    
    int main()
    {
    
        QString qstr = QString::fromUtf8("  𝐺𝐷𝑃 𝑑   𝐺𝐷𝑃𝑑");
        cout << qstr.length() << std::endl;
        for (QChar c : qstr) cout << QString(c).toStdString() << endl;
    }

Got output:

19

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

Expected output:

11

𝐺

𝐷

𝑃

𝑑

𝐺

𝐷

𝑃

𝑑

Qt version:

Package: qt5-default Architecture: amd64 Version: 5.5.1+dfsg-16ubuntu7.7 Multi-Arch: same Priority: optional Section: universe/libs Source: qtbase-opensource-src Origin: Ubuntu

How to fix this?

Upvotes: 2

Views: 235

Answers (1)

Alex
Alex

Reputation: 1031

QString stores a string of 16-bit QChars https://doc.qt.io/qt-5/qstring.html

" 𝐺𝐷𝑃 𝑑 𝐺𝐷𝑃𝑑" string has 4 byte char. following code can be used:

QString str = QString::fromUtf8("  𝐺𝐷𝑃 𝑑   𝐺𝐷𝑃𝑑");
cout << "uint 32b: " << str.toUcs4().size() << endl;


foreach (const uint &  ucsChar, str.toUcs4())
    cout << QChar::decomposition(ucsChar).toStdString() << endl;

Upvotes: 2

Related Questions