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
Go the Project's Properties -> Linker-> System -> SubSystem
, then set it to Console(/S)
.
I found this most useful:
#include <QTextStream>
QTextStream out(stdout);
foreach(QString x, strings)
out << x << endl;
It also has a syntax similar to prinft, e.g.:
qDebug ("message %d, says: %s",num,str);
Very handy as well
"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
.
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.
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.
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();