QT QString from QDataStream

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

I'm working with a buffer and I'm trying to get a string from it, but isnt working...

Example:

*void myFunc(QDataStream& in) {     quint8 v;     in >> v;     // Ok, I caught v value successfuly     QString s;     in >> s;     // Didnt work :< }* 

The string lenght is stored on 2 first bytes...

Thanks

回答1:

If the string was not written as a QString, you need to read its length and content separately.

quint8 v; in >> v;  quint16 length = 0; in >> length;  // the string is probably utf8 or latin QByteArray buffer(length, Qt::Uninitialized);  in.readRawData(buffer.data(), length);  QString string(buffer); 

You might have to change the endianness of the QDataStream with QDataStream::setByteOrder before reading the 16-bit length.



回答2:

We should really see the writing code and how you create the QDataStream. I tried with the following sample, and in this case your function works very well:

#include <QCoreApplication> #include <QDebug> #include <QDataStream> #include <QBuffer>  void myFunc(QDataStream& in) {     quint8 v;     in >> v; qDebug() << v;     // Ok, I caught v value successfuly     QString s;     in >> s; qDebug() << s;     // Didnt work :< }   int main(int argc, char ** argv) {     QCoreApplication a(argc, argv);      QBuffer buffer;     buffer.open(QBuffer::ReadWrite);       // write test data into the buffer     QDataStream out(&buffer);     quint8 ival = 42;     QString sval = "Qt";     out << ival;     out << sval;      // read back data     buffer.seek(0);     myFunc(out);      return a.exec(); } 

Output when executed:

$ ./App  42  "Qt"  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!