HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

How to convert QString to std::string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howstdconvertstringqstring

Problem

I am trying to do something like this:

QString string;
// do things...
std::cout << string << std::endl;


but the code doesn't compile.
How to output the content of qstring into the console (e.g. for debugging purposes or other reasons)? How to convert QString to std::string?

Solution

One of the things you should remember when converting QString to std::string is the fact that QString is UTF-16 encoded while std::string... May have any encodings.

So the best would be either:

QString qs;

// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();

// or this if you're on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();


The suggested (accepted) method may work if you specify codec.

See: http://doc.qt.io/qt-5/qstring.html#toLatin1

Code Snippets

QString qs;

// Either this if you use UTF-8 anywhere
std::string utf8_text = qs.toUtf8().constData();

// or this if you're on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();

Context

Stack Overflow Q#4214369, score: 257

Revisions (0)

No revisions yet.