How to convert QString to wchar_t*
-
Hi guys,
I want to convert to wchar_t type.
my example:
@wchar_t* Utility::converToWChar_t(QString text){
qDebug()<<text.length();
wchar_t* c_Text = new wchar_t[text.length() + 1];
text.toWCharArray(c_Text);
return c_Text;
}@
But result c_Text is itseft with special symbol. how to remove that symbol.
eg:
text = "Hello"
c_Text is: "Hello췍﷽﷽\125653"
Thanks. -
Remove "+ 1" from length declaration.
-
Hi,
If I remove "+1" output is "Hello﷽﷽\125653" @0x5a6310 -
I try to:
@ QString s = "Hello";
wchar_t* ch = new wchar_t[6];
wchar_t* ch2;
s.toWCharArray(ch);
s.toWCharArray(ch2);@
ouput:
ch = "Hello췍﷽﷽\125653" @0x116310
ch2 = "Hello\021愈>" @0x3efa6c
is incorrect, else expect is "Hello" -
The documentation says:
- this function does not append a null character to the array
How are you reading the wchar_t? Maybe you are reading too much data?
-
Append the null terminator ('\0') to the array. Or make sure you read enough bytes (toWCharArray() returns length of created data).
-
@QString s = "Hello";
wchar_t* ch = new wchar_t[s.length()];
s.toWCharArray(ch);@"Hello﷽﷽\125653" @0x466310
character "﷽﷽\125653" always showed at last text. although i allocation memory is right.
-
Hi try:
@
wchar_t * ch = new wchar_t[6];.....
ch[5] = 0;
@edit: oops!
-
Thank you for your answers.
It's resolved. I don't know why you set 7 not 5 because length of text is 5.
Thanks again. -
@
wchar_t* Utility::converToWChar_t(QString text){
qDebug()<<text.length();
wchar_t* c_Text = new wchar_t[text.length() + 1];
text.toWCharArray(c_Text);c_Text[[text.length()] = 0; //Add this line should work as you expected return c_Text; }
@
If you are using windows,
@
(wchar_t*)text.toUtf16()
@can be used.
-
I agree, your first code should work... but maybe the data is not initialised to 0's so you could try:
@
wchar_t* Utility::converToWChar_t(QString text)
{
qDebug()<<text.length();
wchar_t* c_Text = new wchar_t[text.length() + 1];
text.toWCharArray(c_Text);
ch[5] = 0; // or you can use text.length() + 1 - 1 (ok you dont need +1-1)
return c_Text;
}
@Or you can just initialise the array at the start:
@
wchar_t* c_Text = new wchar_t[text.length() + 1];
memset(c_Text, text.length(), 0); // from memory, might be slightly wrong order
@ -
Thank you for your replies.