I need to convert QChar to wchar_t
I tried the following:
#include <cstdlib> #include <QtGui/QApplication> #include <iostream> using namespace std; int main(int argc, char** argv) { QString mystring = "Hello World\n"; wchar_t myArray[mystring.size()]; for (int x=0; x<mystring.size(); x++) { myArray[x] = mystring.at(x).toLatin1(); cout << mystring.at(x).toLatin1(); // checks the char at index x (fine) } cout << "myArray : " << myArray << "\n"; // doesn't give me correct value return 0; }
Oh, and before someone suggests using the .toWCharArray (wchar_t * array) function, I tried this and essentially does the same thing as above and doesn't pass characters as it should.
Below is the code for this if you do not believe me:
#include <cstdlib> #include <QtGui/QApplication> #include <iostream> using namespace std; int main(int argc, char** argv) { QString mystring = "Hello World\n"; cout << mystring.toLatin1().data(); wchar_t mywcharArray[mystring.size()]; cout << "Mystring size : " << mystring.size() << "\n"; int length = -1; length = mystring.toWCharArray(mywcharArray); cout << "length : " << length; cout << mywcharArray; return 0; }
Please help, I have been in this simple problem for several days. Ideally, I would not want to use wchar_t at all, but, unfortunately, a pointer to this type is required in the third function to control the pump using serial RS232 commands.
Thanks.
EDIT: to run this code you need the QT libraries, you can get them by loading the QT creator and getting the output in the console, you will need to add the "CONFIG + = console" command to the .pro file (in the QT creator) or custom definitions in the properties when using the netbeans project.
EDIT:
Thanks to Vlad for his correct answer:
Here is the updated code to do the same, but using the char method of passing char and not forgetting to add null termination.
#include <cstdlib> #include <QtGui/QApplication> #include <iostream> using namespace std; int main(int argc, char** argv) { QString mystring = "Hello World\n"; wchar_t myArray[mystring.size()]; for (int x=0; x<mystring.size(); x++) { myArray[x] = (wchar_t)mystring.at(x).toLatin1(); cout << mystring.at(x).toLatin1(); } myArray[mystring.size()-1] = '\0'; // Add null character to end of wchar array wcout << "myArray : " << myArray << "\n"; // use wcout to output wchar_t's return 0; }
c ++ qt unicode wchar-t qstring
Zac
source share