Anon
Anon

Reputation: 2492

In Qt: Can I output to `stdout`, as easy as I can output to `stderr` using qDebug()?

Up until now, I output everything using qDebug().noquote(). This is easy because it just requires a simple #import <QDebug>

Now I need everything to output to stdout, but I don't know how to do it easily. This how I was taught:

QTextStream cout(stdout, QIODevice::WriteOnly);

However, creating a new object is a tad bit more cumbersome than a simple #import <QDebug>. What is the good/least cumbersome way to handle stdout in qt?

Upvotes: 4

Views: 7393

Answers (2)

Jason Haslam
Jason Haslam

Reputation: 2897

The best way is the one you mentioned. You don't have to create a new local variable:

QTextStream(stdout) << "Hello world!" << Qt::endl;

If the source text is not Latin-1 encoded then you need to convert to QString before passing it to the stream operator:

QTextStream(stdout) << QString::fromUtf8("utf8 literal") << Qt::endl;

Upvotes: 3

MrEricSir
MrEricSir

Reputation: 8242

qDebug(), qInfo(), etc. are all piped to a default message handler. But you can easily install your own that writes the debug strings to a different stream, file, or anything. All you need to do is define a message handler function and install it using qInstallMessageHandler().

Putting it all together, here's a complete example:

#include <QDebug>

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QTextStream cout(stdout, QIODevice::WriteOnly);
    cout << msg << endl;
}

int main(int argc, char *argv[])
{
    qInstallMessageHandler(myMessageOutput);

    qDebug().noquote() << "Hello world!";
}

Upvotes: 8

Related Questions