289

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?

Nejat
  • 31,784
  • 12
  • 106
  • 138
augustin
  • 14,373
  • 13
  • 66
  • 79

12 Answers12

342

You can use:

QString qs;
// do things
std::cout << qs.toStdString() << std::endl;

It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well. Here's reference documentation for QString.

tunafish24
  • 2,288
  • 6
  • 28
  • 47
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • 85
    As of Qt 5.0, `QString::toStdString()` now uses `QString::toUtf8()` to perform the conversion, so the Unicode properties of the string will not be lost (http://qt-project.org/doc/qt-5.0/qtcore/qstring.html#toStdString). – Emile Cormier Apr 14 '13 at 18:13
  • And if you want to check the source code for `QString::toStdString`, [here it is](https://qt.gitorious.org/qt/qtbase/source/9754e5a03e4444a18ec7ca1525d196326ff4e038:src/corelib/tools/qstring.h#L1164). – thuga Oct 02 '14 at 13:29
  • 1
    How can i test to see if it indeed loses the Unicode property? Will using Unicode characters(e.g. say from a language other than English) will do? – Yousuf Azad Aug 23 '16 at 03:48
255

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

Artyom
  • 31,019
  • 21
  • 127
  • 215
  • 1
    This isn't safe & is slightly slower than the proper way. You're accessing the data of a QByteArray created on the stack. The destructor for the QByteArray may be called before the constructor of the STL string. The safest way to create a helper function. `static inline std::string toUtf8(const QString& s) { QByteArray sUtf8 = s.toUtf8(); return std::string(sUtf8.constData(), sUtf8.size()); }` – Vitali Dec 02 '11 at 02:27
  • 18
    @Vitali not correct. "The destructor for the QByteArray may be called before the constructor of the STL string" is not correct statement: Quoting the standard: 12.2.3 Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. And the full expression there is `std::string utf8_text = qs.toUtf8().constData();` So your statement is not correct – Artyom Dec 04 '11 at 13:55
  • That's true - I was thinking about const char *x = qs.ToUtf8().constData(). Still, isn't it easier to just call qs.toStdString()? – Vitali Dec 06 '11 at 14:36
  • 8
    @Vitali No. That loses non-latin1 characters. Try this: `QString s = QString::fromUtf8("árvíztűrő tükörfúrógép ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP"); std::cout << s.toStdString() << std::endl; std::cout << s.toUtf8().constData() << std::endl;`. The first is incorrect, the second is perfect. You need an utf8 terminal to test this. – Notinlist Dec 13 '11 at 22:24
  • 3
    For what it's worth, `.toStdString()` for me always results in an access violation in the pipe operator, irrespective of the `QString`'s contents (non-latin1 or not). This is on Qt 4.8.3/MSVC++ 10/Win 7. – Daniel Saner Nov 19 '12 at 12:37
  • @Artyom The answer should be edited because `QByteArray QString::toAscii() const` is [obsolete](http://doc.qt.io/qt-5/qstring-obsolete.html#toAscii) – Tarod Sep 02 '15 at 11:39
  • @notinlist Well, both methods result in the same giberish: "∩┐╜rv∩┐╜zt?r? t∩┐╜k∩┐╜rf∩┐╜r∩┐╜g∩┐╜p ∩┐╜RV∩┐╜ZT?R? T∩┐╜K∩┐╜RF∩┐╜R∩┐╜G∩┐╜P". They are the same at least. – Laszlo Dec 15 '19 at 20:47
  • https://stackoverflow.com/a/4214397/8533873 should be the accepted answer. – IceBerg0 Aug 30 '21 at 12:10
  • @Artyom I have an issue, while use `toLocal8Bit().constData()`. One file come from U disk, and it's filename with code page `GB2312`, then open it in english area windows, it's code page is `ISO 8859-1`. So, at this moment, if you pass QString to std::string, you will get an error encode. How to fix it? – Shun Apr 10 '23 at 08:28
37

If your ultimate aim is to get debugging messages to the console, you can use qDebug().

You can use like,

qDebug()<<string; which will print the contents to the console.

This way is better than converting it into std::string just for the sake of debugging messages.

liaK
  • 11,422
  • 11
  • 48
  • 73
26
QString qstr;
std::string str = qstr.toStdString();

However, if you're using Qt:

QTextStream out(stdout);
out << qstr;
chris
  • 3,986
  • 1
  • 26
  • 32
  • I had tried out << qstr first, before asking, but it didn't compile. It works with qstr.toStdString(), though. – augustin Nov 18 '10 at 12:38
  • 4
    I don't think so. You tried std::cout << qstr, not QTextString(stdout) << qstr; – chris Nov 18 '10 at 12:42
19

Best thing to do would be to overload operator<< yourself, so that QString can be passed as a type to any library expecting an output-able type.

std::ostream& operator<<(std::ostream& str, const QString& string) {
    return str << string.toStdString();
}
Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 4
    Why the down votes, folks? It's an overkill in my case, but who knows, it might be useful (to me or someone else). – augustin Nov 18 '10 at 12:39
  • I like this because Qt have a habit of changing the way their strings work - and this puts the conversion in one place. – Den-Jason Aug 28 '19 at 10:48
13

An alternative to the proposed:

QString qs;
std::string current_locale_text = qs.toLocal8Bit().constData();

could be:

QString qs;
std::string current_locale_text = qPrintable(qs);

See qPrintable documentation, a macro delivering a const char * from QtGlobal.

flokk
  • 714
  • 8
  • 15
  • 2
    this works even with a Qt-Build with `-no-stl`-Option set. [some more info](http://asmaloney.com/2011/11/code/qstringtostdstring-qstringfromstdstring-and-no-stl/) – Senči Jun 20 '13 at 13:40
8

The simplest way would be QString::toStdString().

cbuchart
  • 10,847
  • 9
  • 53
  • 93
shaveenk
  • 1,983
  • 7
  • 25
  • 37
2

You can use this;

QString data;
data.toStdString().c_str();
1

There is also the option to use qPrintable or qUtf8Printable

E.g.:

#include <QString>
#include <iostream>

int main()
{
    QString myString = "Hello World";

    // Using qPrintable
    std::cout << "qPrintable: " << qPrintable(myString) << std::endl;

    // Using qUtf8Printable
    std::cout << "qUtf8Printable: " << qUtf8Printable(myString) << std::endl;

    return 0;
}
NovoG93
  • 21
  • 1
0
 QString data;
   data.toStdString().c_str();

could even throw exception on VS2017 compiler in xstring

 ~basic_string() _NOEXCEPT
        {   // destroy the string
        _Tidy_deallocate();
        }

the right way ( secure - no exception) is how is explained above from Artyom

 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();
JPM
  • 69
  • 5
0

HA~I finally find the answer which I can run! Share to you now~

QString qStr = "Hello world";
QByteArray qByteArray = qStr.toUtf8();
char* cStr = qByteArray.data();
const char* test = cStr;
qDebug()<<test<<endl;
KinverChan
  • 11
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 03 '23 at 10:24
-2

Try this:

#include <QDebug>
QString string;
// do things...
qDebug() << "right" << string << std::endl;
bunbun
  • 2,595
  • 3
  • 34
  • 52
  • 2
    The question is very clear: convert QString to std::string, not to print it. – eyllanesc Dec 12 '18 at 02:58
  • 2
    @eyllanesc the question text says "How to output the content of qstring into the console?" , it seems OP assumes converting to std::string is the only way. It's really two questions being asked at once . – M.M Mar 09 '20 at 21:48
  • @M.M The question seems unclear since the question in the title says *How to convert QString to std::string?*, Maybe it's an XY problem. – eyllanesc Mar 09 '20 at 21:51