How to print to console when using Qt

前端 未结 12 1707
执笔经年
执笔经年 2020-11-29 15:59

I\'m using Qt4 and C++ for making some programs in computer graphics. I need to be able to print some variables in my console at run-time, not debugging, but cout

相关标签:
12条回答
  • 2020-11-29 16:21

    Go the Project's Properties -> Linker-> System -> SubSystem, then set it to Console(/S).

    0 讨论(0)
  • 2020-11-29 16:27

    I found this most useful:

    #include <QTextStream>
    
    QTextStream out(stdout);
    foreach(QString x, strings)
        out << x << endl;
    
    0 讨论(0)
  • 2020-11-29 16:34

    It also has a syntax similar to prinft, e.g.:

    qDebug ("message %d, says: %s",num,str); 
    

    Very handy as well

    0 讨论(0)
  • 2020-11-29 16:36

    "build & run" > Default for "Run in terminal" --> Enable

    to flush the buffer use this command --> fflush(stdout); you can also use "\n" in printf or cout.

    0 讨论(0)
  • 2020-11-29 16:37

    Writing to stdout

    If you want something that, like std::cout, writes to your application's standard output, you can simply do the following (credit to CapelliC):

    QTextStream(stdout) << "string to print" << endl;
    

    If you want to avoid creating a temporary QTextStream object, follow Yakk's suggestion in the comments below of creating a function to return a static handle for stdout:

    inline QTextStream& qStdout()
    {
        static QTextStream r{stdout};
        return r;
    }
    
    ...
    
    foreach(QString x, strings)
        qStdout() << x << endl;
    

    Remember to flush the stream periodically to ensure the output is actually printed.

    Writing to stderr

    Note that the above technique can also be used for other outputs. However, there are more readable ways to write to stderr (credit to Goz and the comments below his answer):

    qDebug() << "Debug Message";    // CAN BE REMOVED AT COMPILE TIME!
    qWarning() << "Warning Message";
    qCritical() << "Critical Error Message";
    qFatal("Fatal Error Message");  // WILL KILL THE PROGRAM!
    

    qDebug() is closed if QT_NO_DEBUG_OUTPUT is turned on at compile-time.

    (Goz notes in a comment that for non-console apps, these can print to a different stream than stderr.)


    NOTE: All of the Qt print methods assume that const char* arguments are ISO-8859-1 encoded strings with terminating \0 characters.

    0 讨论(0)
  • 2020-11-29 16:37

    What variables do you want to print? If you mean QStrings, those need to be converted to c-Strings. Try:

    std::cout << myString.toAscii().data();
    
    0 讨论(0)
提交回复
热议问题