I have been wondering if it is possible to collect user input using the qDebug()
statement in Qt C++.
I tried do it like in the std C++ code like:
qDebug() >> myvar;
but it didn't work.
How can I read from stdin
using Qt?
I have been wondering if it is possible to collect user input using the qDebug()
statement in Qt C++.
I tried do it like in the std C++ code like:
qDebug() >> myvar;
but it didn't work.
How can I read from stdin
using Qt?
qDebug
is used to make output to stderr
. If you want to read from stdin
using Qt, you should use QTextStream
:
#include <stdio.h>
QTextStream in(stdin);
QString line;
in >> line;
Since you want to use QDebug, I presume the input might be for debug purposes. In that case, if it is a GUI application, you might consider using QInputDialog to launch a modal dialog to get the input. It has a bunch of static convenience methods, but as an example, to get a string you could do this:
qDebug() << "before debug input dialog";
QString debugText = QInputDialog::getText(NULL, "Input debug text", "Your input:");
qDebug() << "got text" << debugText;
The difference with this, and simply reading from stdin is, this will not block the whole event loop (it will disable the GUI in the usual modal dialog way). In contrast, simple read from stdin will block the whole event loop. Wether this is irrelevant in debug situation, or if you specifically want one or the other, depends on what else is happening in the event loop (like, network stuff). However, if you use stdin for other purposes, then this dialog trick can be very handy.
qDebug
and friends write text to an appropriate location. This can be stderr, but it can be a system log just as well. Thus not all locations where qDebug
writes to even support user input. But even if they would: How could Qt determine if user input should go to qDebug
, qWarning
, or one of the others? It's not possible.