Ratman
Ratman

Reputation: 113

Wrong output of qDebug() (UTF - 8)

I'm trying to store a string with special chars::

qDebug() << "ÑABCgÓ";

Outputs: (here i can't even type the correct output some garbage is missing after à & Ã) ÃABCgÃ

I suspect some UTF-8 / Latin1 / ASCII, but can't find the setting to output to console / file. What i have written in my code : "ÑABCgÓ".

(Qt:4.8.5 / Ubunto 12.04 / C++98)

Upvotes: 4

Views: 4031

Answers (2)

L&#225;szl&#243; Papp
L&#225;szl&#243; Papp

Reputation: 53173

You could use the QString QString::fromUtf8(const char * str, int size = -1) [static] as the sample code presents that below. This is one of the main reasons why QString exists.

See the documentation for details:

http://qt-project.org/doc/qt-5.1/qtcore/qstring.html#fromUtf8

main.cpp

#include <QString>
#include <QDebug>

int main()
{
    qDebug() << QString::fromUtf8("ÑABCgÓ");
    return 0;
}

Building (customize for your scenario)

g++ -fPIC -I/usr/include/qt -I/usr/include/qt/QtCore -lQt5Core main1000.cpp && ./a.out

Output

"ÑABCgÓ"

That being said, depending on your locale, simply qDebug() << "ÑABCgÓ"; could work as well like in here, but it is recommended to make sure by explicitly asking the UTF-8 handling.

Upvotes: 4

Leo Chapiro
Leo Chapiro

Reputation: 13984

Try this:

 QTextCodec *codec = QTextCodec::codecForName("UTF-8");
 QTextCodec::setCodecForCStrings(codec);
 qDebug() << "ÑABCgÓ";

Upvotes: 1

Related Questions