我需要将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创建者并在控制台中获取输出来获取这些库如果使用NetBeans项目,则QT Creator)或属性下的自定义定义。

编辑:

感谢下面的弗拉德(Vlad)的正确答复:

这是要执行相同操作的更新代码,但是使用Char方法转移CHAR并记住添加零终止。

#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;
}
有帮助吗?

解决方案

这是转换的示例 QString 两者兼而有之 std :: WstringWCHAR_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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top