Search code examples
c++qt4qtextstream

QTextStream stdin readline not pausing for input


Here is a very simple application to illustrate the problem I am having.

#include <QTextStream>

int main()
{
    QTextStream cin(stdin);
    QTextStream cout(stdout);

    QString test;

    cout << "Enter a value: ";
    cout.flush();
    cin >> test;

    cout << "Enter another value: ";
    cout.flush();

    test = cin.readLine();
    cout << test;
    return 0;
}

I expect execution to pause and wait for input at test = cin.readline();, but it does not. If I remove cin >> test; then it pauses.

Why is this code behaving like this and how do I get behaviour I want?


Solution

  • Probably the buffer still has a endline character '\n' that is accepted by cin.readLine(); - try flushing it with cin.flush() before executing cin.readLine().


    This code is working:

    QTextStream cin(stdin);
    QTextStream cout(stdout);
    
    QString test;
    
    cout << "Enter a value: ";
    cout.flush();
    cin >> test;
    
    cout << "Enter another value: ";
    cout.flush();
    cin.skipWhiteSpace(); //Important line!
    test = cin.readLine();
    cout << test;
    return 0;
    

    You just need to add cin.skipWhiteSpace() before cin.readLine(), as I said before the '\n' character is still in buffer and that method is getting rid of it.