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.
-
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).
-
@
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
@