Important: Please read the Qt Code of Conduct -

Problem with QStream adding Extra Characters After a flush?

  • I have a work around but do not understand why I am experiencing this problem.

    I am using QT 5.6 on Ubuntu (not sure what version).

    I have the following code:

        #include <QCoreApplication>
        #include <QDebug>
        #include <QFile>
    int main(int argc, char *argv[])
        QCoreApplication a(argc, argv);
        bool ok = false, second = false;
        double dr = 0.0;
        double dm = 0.0;
        QString tofile;
        QTextStream debug(&tofile);
        QString line = "the cow jumped over the moon 100.0 -1.0 foo bar";
        QString buffer;
        QTextStream bufferstream(& buffer);
        QStringList list = line.split(" ");
        foreach(buffer, list){
            debug<< "buffer before stream: " << buffer << '\n';
            buffer.toDouble( &ok );
            if(ok == true && second == true ){//found second valid double
                bufferstream >> dm;
                debug<< "buffer after stream and flush: "<< buffer << '\n';
            if(ok == true && second == false){//found the first valid double
                second = true;
                bufferstream >> dr;
                debug<< "buffer first stream: " << buffer << '\n';
        debug<< "dm: "<< dm << "dr: "<< dr;
        qDebug()<< tofile;
        QFile file("StreamTestFile.txt");
        if (! | QFile::Text)) {
        QTextStream out(&file);
        out << tofile;
        return a.exec();

    After the second stream to extract the second double it adds characters, here is the output

    buffer before stream: the
    buffer before stream: cow
    buffer before stream: jumped
    buffer before stream: over
    buffer before stream: the
    buffer before stream: moon
    buffer before stream: 100.0
    buffer first stream: 100.0
    buffer before stream: -1.0
    buffer after stream and flush: -1.\00
    dm: 0dr: 100

    so you do not get the correct double. Any explanation? I fixed it by making new QTextStreams in each if statement...

    just tried this in Windows (minGW) and got the same thing.

  • Moderators

    You're doing it wrong. Just use the stream to read from the string:

    QString line = "the cow jumped over the moon 100.0 -1.0 foo bar", word;
    QTextStream in(&line);
    while (!in.atEnd())  {
        in >> word;
        bool ok;
        double value = word.toDouble(&ok);
        if (!ok)
         // ...

  • @kshegunov

    Yeah thanks I am aware of that method.

    Frankly have been reading a bit and 'discovered' the stream method to convert from QString to double and thought, 'Oh Cool let's do this!!" .

    Then I ran into the problem shown above. I guess I am one of the few people crazy enough to try it.

    Still appreciate the feedback thanks.

Log in to reply