Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QTextStream write to QString ignore endl



  • My program is simple

    #include <QTextStream>
    #include <QDebug>
    #include <QString>
    
    int main(int argc, char *argv[])
    {
        QString msg;
        QTextStream stream(&msg, QIODevice::Text | QIODevice::WriteOnly);
        stream << "1" << endl;
        stream << "2" << endl;
        stream << "3";
        qDebug() << msg;   // Output "1\n2\n3"
        return 0;
    }
    
    

    What I want is as follows :

    1
    2
    3
    

    But it is seems that QTextStream totally ignore the endl manipulator. The program output is :

    1\n2\n3
    

    Besides endl, I have already tried '\n', '\r\n', but not work too.

    My platform is Windows 11, the Qt version is 5.12.11(MSVC2017 64bit), and the compiler is MSVC.

    Any one can help?


  • Moderators

    Hi, and welcome!

    @semicloud said in QTextStream write to QString ignore endl:

    1\n2\n3

    That is correct. \n is the string value of endl. This is the same debug output as qDebug() << QString("1\n2\n3");.

    What I want is as follows :

    1
    2
    3
    

    You can do one of the following:

    • Write msg to a text file and open it with a text editor.
    • Put msg in a QLabel or QTextEdit.
    • Convert msg from a QString to a const char*: qDebug() << msg.toUtf8().constData();

Log in to reply