• 6503阅读
  • 1回复

Qt4.6 QDataStream 示例代码的问题 [复制链接]

上一主题 下一主题
离线xxf_cz
 
只看楼主 倒序阅读 楼主  发表于: 2009-12-16
Qt4.6,QDataStream类的参考文档中写道:

Example (write binary data to a stream):

  1. QFile file("file.dat");
  2. file.open(QIODevice::WriteOnly);
  3. QDataStream out(&file);   // we will serialize the data into the file
  4. out << "the answer is";   // serialize a string
  5. out << (qint32)42;        // serialize an integer


Example (read binary data from a stream):
  1. QFile file("file.dat");
  2. file.open(QIODevice::ReadOnly);
  3. QDataStream in(&file);    // read the data serialized from the file
  4. QString str;
  5. qint32 a;
  6. in >> str >> a;           // extract "the answer is" and 42


我原样搬进了程序中测试一下,结果你猜怎么着?

42被读出来了,但原先写入的字符串"the answer is" 读出以后变成了乱码:


把程序中写入部分修改一下:
  1. out << (QString)"the answer is";   // serialize a string


就OK了。
不知道为什么示例代码不对,请高人指点一下。
[ 此帖被xxf_cz在2009-12-16 21:31重新编辑 ]
离线dbzhang800

只看该作者 1楼 发表于: 2009-12-16
我看了一下manual,没发现你说的这个错误
http://qt.nokia.com/doc/4.6/qdatastream.html


至于,你提到的问题,是下面两个函数的区别

QDataStream &   operator<< ( const char * s )

QDataStream &   operator<< ( QDataStream & stream, const QString & string )

注意,它们都存在一个相应的 >> 的函数,配对使用不会错,但不可混用!!

二者存储方式不一样,对此,manual中有详细的 format 说明
快速回复
限100 字节
 
上一个 下一个