繁体   English   中英

QChar到wchar_t

[英]QChar to wchar_t

我需要将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创建者获取这些代码并在控制台中获取输出,您必须将命令“CONFIG + = console”添加到.pro文件中(在QT创建者)或使用netbeans项目时属性下的自定义定义。

编辑:

感谢Vlad下面的正确答复:

这是更新的代码,用于执行相同的操作,但使用char方法传递char并记住添加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;
}

以下是将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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM