可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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"