0

This input is redirected from file to the executable in a unix terminal:

10 1 2 3 4 5 6 7 8 9 10
5 10 20 30 40 50

Cin doesn't wait for input even though it seems to be in a good state to do so.

int main(void) {
    std::cout << "GOOD: " << std::cin.good() << std::endl
              << "EOF: " << std::cin.eof() << std::endl
              << "FAIL: " << std::cin.fail() << std::endl
              << "BAD: " << std::cin.bad() << "\n\n";
    int s;
    while(std::cin >> s) {
            int * arr = new int[s];
            for(int i = 0; i < s; i++) {
                    std::cin >> arr[i];
                    std::cout << arr[i] << " ";
            }
            std::cout << "\n\n";
            delete[] arr;
    }

    std::cout << "CAN READ: " << (bool)(std::cin >> s) << std::endl
              << "GOOD: "<< std::cin.good() << std::endl
              << "EOF: "<< std::cin.eof() << std::endl
              << "FAIL: "<< std::cin.fail() << std::endl
              << "BAD: "<< std::cin.bad() << "\n\n";

    std::cin.clear();
    std::cin.ignore(INT_MAX);

    std::cout << "GOOD: " << std::cin.good() << std::endl
              << "EOF: " << std::cin.eof() << std::endl
              << "FAIL: " << std::cin.fail() << std::endl
              << "BAD: " << std::cin.bad() << "\n\n";

    std::cin.clear();

    std::cout << "GOOD: " << std::cin.good() << std::endl
              << "EOF: " << std::cin.eof() << std::endl
              << "FAIL: " << std::cin.fail() << std::endl
              << "BAD: " << std::cin.bad() << "\n\n";

    std::cout << "Enter a #:\n";
    std::cin >> s; // unable to provide input (EDIT: from keyboard) here
    std::cout << s << std::endl; 

    std::cout << "Program ends.\n";
    return 0;
}

The output is

GOOD: 1
EOF: 0
FAIL: 0
BAD: 0

1 2 3 4 5 6 7 8 9 10 

10 20 30 40 50

CAN READ: 0
GOOD: 0
EOF: 1
FAIL: 1
BAD: 0

GOOD: 0
EOF: 1
FAIL: 0
BAD: 0

GOOD: 1
EOF: 0
FAIL: 0
BAD: 0

Enter a #:
5
Program ends.

What am I missing here? Why doesn't cin allow me to provide it input even though its buffer is empty and the stream is in a good state? What can I do to get cin to accept further input here?

Joey
  • 43
  • 1
  • 4

2 Answers2

0

Thought it was possible to seamlessly obtain keyboard input after redirecting a file to cin (thanks to Artemy Vysotsky for helping me realize that this is not the case).

For anyone that has a similar problem, std::cin.rdbuf() can be used. Details here: Can std::cin switch from accepting file input to keyboard input at run-time?

Joey
  • 43
  • 1
  • 4
0

use cin.flush(); after taking input an integer. It will flush the stream and you can take the string input again. If you want to know why it happens you can read it here

Saram Ali Azhar
  • 234
  • 1
  • 18