Suppose I have a program that accepts input from the keyboard, or alternatively accepts redirected input from a file such that:
#include <iostream>
using namespace std;
int main() {
string str;
while (getline(cin, str)) {
if(str.compare("exit") == 0)
return 0;
}
return 0;
}
In this implementation, I expect that an instance of the program using keyboard input will terminate upon typing "exit", and that an instance of the program using file input will terminate upon EOF.
I would like to implement functionality such that if an instance of the program is running that uses file input, it will allow for keyboard input upon reaching EOF, instead of terminating. I have done some research which suggests that this isn't possible with getline
as the condition for the while loop, because it will return false once the file input ends, and I don't know of a way to tell cin
that I want to accept keyboard input at that time.
So, is it possible for cin
to switch from accepting file input to instead accepting keyboard input while the file is running? If it is not, could you explain why?