[Qt-interest] Convert a QString to string

NARCISO, Rui RUI.NARCISO at airbus.com
Tue Feb 10 17:04:24 CET 2009


wouldn't :

   str(your_QString)

solve the problem ??

Rui

-----Message d'origine-----
De : qt-interest-bounces at trolltech.com
[mailto:qt-interest-bounces at trolltech.com]De la part de Thiago Macieira
Envoyé : mardi 10 février 2009 16:00
À : qt-interest at trolltech.com
Objet : Re: [Qt-interest] Convert a QString to string


Em Terça-feira 10 Fevereiro 2009, às 15:05:18, Jan Ekholm escreveu:
> On Tuesday 10 February 2009, Sujan Dasmahapatra wrote:
> > How can I convert a    QString  str1 to string str2.
>
> Assuming you mean std::string it's pretty obvious if you actually look into
> the docs a bit...
>
> 	std::string QString::toStdString () const

Please be careful with that function.

std::string is not a string (in the Qt sense), but a byte array. It's closer 
to QByteArray than to QString. That means that, when you convert from QString 
to std::string, you're introducing an encoding conversion and you should, 
therefore, be very careful.

Unlike the conversions to QByteArray, QString offers no choice of encoding for 
the conversion to std::string. Your only option is the toAscii() conversion, 
which is Latin 1 by default but can be changed with 
QTextCodec::setCodecForCStrings. This is important, because it's not the 
locale conversion: you may be losing data by converting to std::string.

My recommendation is that you instead modify the rest of your code to use 
QString, as far as you can. 

If you can't, then try to use std::wstring instead: all platforms where Qt is 
supported use UTF-16 or UCS-4 for wchar_t, so there's the conversion is 
trivial and there's no loss of data.

-- 
Thiago Macieira - thiago.macieira (AT) nokia.com
  Senior Product Manager - Nokia, Qt Software
     Sandakerveien 116, NO-0402 Oslo, Norway

This mail has originated outside your organization, either from an external partner or the Global Internet.
Keep this in mind if you answer this message.



The information in this e-mail is confidential. The contents may not be disclosed or used by anyone other then the addressee. Access to this e-mail by anyone else is unauthorised.
If you are not the intended recipient, please notify Airbus immediately and delete this e-mail.
Airbus cannot accept any responsibility for the accuracy or completeness of this e-mail as it has been sent over public networks. If you have any concerns over the content of this message or its Accuracy or Integrity, please contact Airbus immediately.
All outgoing e-mails from Airbus are checked using regularly updated virus scanning software but you should take whatever measures you deem to be appropriate to ensure that this message and any attachments are virus free.





More information about the Qt-interest-old mailing list