Qt console application reading issues

When I try to get input from a Qt console application, the program does not work as I expect. The following works as expected:

#include <QCoreApplication>
#include <QTextStream>

QTextStream cout(stdout);
QTextStream cin(stdin);

int main()
{
    QString msg("Hello world!");
    cout << msg << endl;

    return 0;
}

Output:

Hello world!

But as soon as I add

... 
int main()
{
    QString msg("Hello world!");
    cout << msg << endl;

    cout << "Enter new message: ";
    msg = cin.readLine();
    cout << endl << msg << endl;

    return 0;
}

Output:

Hello world!

but then the program waits for input before displaying a prompt for text input, instead of displaying a prompt first, and THEN reading the input. Entered text is displayed along with (after) an input prompt.

I tried to solve this for several hours to no avail.

+4
source share
2 answers

you should clear the output stream:

<Preview> cout. flush ();

which can also be written

(cout << "Enter new message: ").flush();
+3
source

:

cout << "Enter new message: " << flush;
  • std::flush stdout.
  • std::endl stdout, .
+1

Source: https://habr.com/ru/post/1630077/


All Articles