PDA

View Full Version : How to copy(convert) QString to char* ??



Gokulnathvc
19th April 2011, 08:24
I am having the following codes::


char * size;
QString str;
str.sprintf("Size %s",value);



How to copy the str value to size??? please help me

mcosta
19th April 2011, 08:42
size is a pointer, then you cannot copy directly the contents of str in size.

you have to allocate memory for size. For example


size = new char [str.size() + 1];
memcpy (size, qPrintable(str), str.size());
size[str.size()] = '\0';

Gokulnathvc
19th April 2011, 08:48
It works, But am getting some unknown characters following the correct data.....

ChrisW67
19th April 2011, 09:10
It may work, but it will also be a memory leak if you do not delete the memory after use.

The "unknown characters" will be the toLocal8Bit() conversion of whatever was in the your string. The returned byte array is undefined if the string contains characters not supported by the local 8-bit encoding. Since we cannot see what is your string we cannot tell you what is going on.

How do you intend to actually use the size variable after you have copied the string?

mcosta
19th April 2011, 09:46
what is the value of "value" ???

schnitzel
20th April 2011, 02:31
did you notice this in the QString::sprintf documentation:



Warning: We do not recommend using QString::sprintf() in new Qt code. Instead, consider using QTextStream or arg(), both of which support Unicode strings seamlessly and are type-safe. Here's an example that uses QTextStream:
QString result;
QTextStream(&result) << "pi = " << 3.14;
// result == "pi = 3.14"


Then also look at QString::arg.

DanH
20th April 2011, 03:57
You can assign the value in str to size with:

QByteArray ar = str.toAscii(); // or toLatin1 or toLocal8Bit
size = ar.data();

However, size will be referencing the bytes in the QByteArray object and will go "poof" if/when the QByteArray is destructed.

Otherwise, you can do:

QByteArray ar = str.toAscii();
size = new char[ar.count() + 1];
memcpy(size, ar.constData(), ar.count() + 1);

and then size will "own" its own copy of the data (and it will need to be explicitly deleted later).