简体   繁体   中英

QTextStream provides empty string

What is wrong with this code? (In a Qt environment I wanted to use the QTextStream, but the resulting string is empty. With string the code works OK. BTW: is there any specific reason why Qt does not support directly commonly used templates like vector and string?)

    QString MyFileName;
    QTextStream ts; 
    ts << DirName.c_str() 
       << QDate::currentDate().toString("_yyyy_MM_dd.log").toStdString().c_str() 
       << " (" << ++VolumeNumber << ")";
    ts >> MyFileName;
    string FileName= MyFileName.toStdString();

With standard stream it is much simpler:

   ostringstream oss;
    oss << DirName.c_str() << QDate::currentDate().toString("_yyyy_MM_dd.log").toStdString().c_str() << " (" << ++VolumeNumber << ")";
    FileName= oss.str();

What is the advantage of the Qt approach?

It is because you do not assign any device to QTextStream . It operates on QIODevice (you can also use QString , internally will be proxied by QTextStream through QBuffer ) so it does nothing. You should do:

QString buffer;
QTextStream ts(&buffer);

after you inputted the data the device is set at the end so reading from it gives you empty string so that is another error. To read from it you would need to reset the device with:

ts.device()->reset();

that will move the underlying device to the beginning. If it is a random access device you could seek to certain location and start there.

Still what you want will not work because you serialize something else than you are trying to deserialize (all the problems above not withstanding). You should compose the string you serialize first, serialize it with QTextStream and deserialize it again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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