PDA

View Full Version : QDataStream >> QString



smalls
17th January 2006, 19:42
hi all,

i was struggling with putting a qstring into a qdatastream and getting it out again.
reading through the 4.0 docu's fortune client example it seemed to me that a QString str, when written to a QDataStream, needed str.length bytes.
but this is wrong. it should be 2*length + 4 (every letter in the string gets encoded with 2 bytes and the strings length goes at the beginning encoded with a 4 bytes int) right?

and another thing (which is actually my question) is the following:



// sender
QDataStream stream(socket);
stream << some_QString;
stream << some_quint;

// receiver
QDataStream stream(socket);
stream >> some_QString;


i found out that in my case the receiver gets an exact copy of some_QString and that the following integer is not read. which makes sence after finding out that QString is serialized such that it carries its own length with it. but can i count on that? i'm sending strings followed by ints. so can i just read the strings like that:



stream >> some_QString;


when i know it is followed by an int. or should i still take care by myself that i dont mix up string and int??

wysota
17th January 2006, 20:58
If you write to a descriptor using QDataStream, you can safely read from it using a QDataStream. The problem is only if you write using a QDataStream and read without using it or vice versa.

Codepoet
17th January 2006, 23:14
The idea behind QDataStream is that you can serialize anything with it one time and later deserialize it . So what you put in the stream you have to read back in the same order: No extra counter needed.

The correct receiver for your sender would be:


stream >> some_QString;
stream >> some_quint;


What is not guaranteed is how your data is stored - only that you get later an exact copy back.