Hello,
I need to convert a QChar to a wchar_t
I've 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've tried that and it essentially does the same thing as above and does not transfer characters as it should.
Below is the code for that if you don't 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've been at this simple problem for days. I'd ideally like to not use wchar_t's at all but unfortunately a pointer to this type is required in a third party function to control a pump using serial RS232 commands.
Thanks.
EDIT: To run this code you will need the QT libraries, you can get these by downloading QT creator and to get the output in the console you'll have to add the command "CONFIG += console" to the .pro file (in QT creator) or to the custom definitions under properties if using a netbeans project.
EDIT:
Thanks to Vlad below for his correct response:
Here is the updated code to do the same thing but using a transfer char by char method and remembering to add the 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;
}