我需要将QChar转换为wchar_t
我尝试过以下几种方法:
#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;
}哦,在有人建议使用.toWCharArray(wchar_t*数组)函数之前,我已经尝试过了,它基本上做了与上面相同的事情,并且不像它应该做的那样传输字符。
如果你不相信我,下面是代码:
#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;
}请帮帮忙,这个简单的问题我已经解决了好几天了。理想情况下,我希望根本不使用wchar_t,但不幸的是,在使用串行RS232命令控制泵的第三方函数中需要指向这种类型的指针。
谢谢。
编辑:要运行此代码,您将需要QT库,您可以通过下载QT creator获得这些库,要在控制台中获得输出,您必须将命令"CONFIG“添加到.pro文件(在QT creator中),或者添加到属性下的自定义定义(如果使用+=项目)。
编辑:
感谢下面Vlad的正确回答:
下面是执行相同操作的更新代码,但使用了一个逐个字符的传输方法,并记住添加了null终止。
#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;
}发布于 2010-09-16 21:13:15
下面是将QString转换为std::wstring和wchar_t数组的示例:
#include <iostream>
#include <QtCore/QString>
using namespace std;
int main ()
{
// Create QT string.
QString qstr = "Hello World";
// Convert it into standard wstring.
std::wstring str = qstr.toStdWString ();
// Get the wchar_t pointer to the standard string.
const wchar_t *p = str.c_str ();
// Output results...
wcout << str << endl;
wcout << p << endl;
// Example of converting to C array of wchar_t.
wchar_t array[qstr.size () + 1];
int length = qstr.toWCharArray (array);
if (length < 0 || length >= sizeof(array) / sizeof (array[0]))
{
cerr << "Conversion failed..." << endl;
return 1;
}
array[length] = '\0'; // Manually put terminating character.
wcout << array << endl; // Output...
}请注意,将QString转换为数组更容易出错,要输出unicode字符串,您必须使用std::wcout而不是std::cout,后者是相同的输出流,但对于wchar_t。
https://stackoverflow.com/questions/3726805
复制相似问题