【发布时间】:2011-04-13 05:05:13
【问题描述】:
我需要将 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* array) 函数之前,我已经尝试过了,它基本上做了与上面相同的事情,并且不会按应有的方式传输字符。
如果你不相信我,下面是代码:
#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 += console”添加到 .pro文件(在 QT 创建器中)或属性下的自定义定义(如果使用 netbeans 项目)。
编辑:
感谢以下弗拉德的正确回复:
这是执行相同操作的更新代码,但使用逐字符传输方法并记住添加空终止。
#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;
}
【问题讨论】:
-
就像 Vlad 在下面指出的那样,除了使用 cout 进行 wchar_t 字符串输出之外,您的代码基本上是正确的。将最后一个 cout 更改为 wcout 会给你正确的结果。
标签: c++ qt unicode wchar-t qstring