3

I'm trying that sample code and it crashes, in visualc++ 2010

QString fileName = "helloworld";
std::string str = fileName.toStdString();
ymoreau
  • 3,402
  • 1
  • 22
  • 60
Moaz ELdeen
  • 249
  • 2
  • 3
  • 10
  • does visual studio know what a QString is? I believe you need to link your application aggainst some qt library. – Ivaylo Strandjev Jun 25 '12 at 14:58
  • 2
    @izomorphius, I guess if it compiles then VS "knows" what's QString is. – Roee Gavirel Jun 25 '12 at 15:00
  • Is it possible that your Qt libraries are compiled against a different `std::string` than your compiler install is using? If the Qt libraries were compiled against VC2008, for example, that could cause the crash you're seeing. Particularly the case for VC2010, where (IIRC) significant chunks of the standard library have been changed to better match C++11. – Managu Jun 25 '12 at 15:06

2 Answers2

10

How to convert QString to std::string?

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.

QString qs;

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

// or this if you on Windows :-)
std::string current_locale_text = qs.toLocal8Bit().constData();
Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • 2
    .toStdString() call toAscii() internally so you don't need to know what qt uses itself – Martin Beckett Jun 25 '12 at 15:24
  • @Martin Beckett - thank you, you're correct. ALSO: I forgot to mention the "QtTextCodec" class: http://doc.qt.nokia.com/4.6/qtextcodec.html – paulsm4 Jun 25 '12 at 15:39
1

std::string str(fileName.toStdString()); if you want str to contain a copy of the qstring

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263