Precautions for converting qstring to char *

Source: Internet
Author: User

I recently wrote a QT program. Convert qstring to char * pointer. As a result, a serious program crash error occurs. With a lot of help debugging, we found that when converting qstring to char *, we must define a qbatearray variable.Cannot be connected


.

The following is an official reply:

 

How can I convert a qstring to char * and vice versa? (Trolltech)
Answer:
In order to convert a qstring to a char *, then you first need to get a Latin1 representation of the string by calling tolatin1 () on it which will return a qbytearray. then call data () on the qbytearray to get a pointer to the data stored in the byte array. see the documentation:
See the following example for a demonstration:

Int main (INT argc, char ** argv)
{
Qapplication app (argc, argv );
Qstring str1 = "test ";
Qbytearray BA = str1.tolatin1 ();
Const char * c_str2 = ba. Data ();

Printf ("str2: % s", c_str2 );
Return app.exe C ();
}
Note that it is necessary to store the bytearray before you call data () on it, a call like the following
Const char * c_str2 = str2.tolatin1 (). Data ();
Will make the application crash as the qbytearray has not been stored and hence no longer exists.

To convert a char * To A qstring you can use the qstring constructor that takes a qlatin1string, e. g:
Qstring string = qstring (qlatin1string (c_str2 ));

 

Almost gave QT a mental breakdown.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.