1

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?

Leon
  • 12,013
  • 5
  • 36
  • 59

1 Answers1

6

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.

Mikołaj Mularczyk
  • 959
  • 12
  • 20
  • 1
    I checked it on my computer, I am pretty sure that is about '\n' character, when you execute cin.readLine(); twice it is pausing. – Mikołaj Mularczyk Oct 04 '14 at 11:05
  • You are correct. It seems you need to clear the buffer first. Here is something similar, but I'm not sure yet how to apply this is a QT context http://stackoverflow.com/questions/257091/how-do-i-flush-the-cin-buffer – Leon Oct 04 '14 at 11:20