The following code simply echoes the standard input to the standard output. If I run the program like so ./a.out, I can type anything and the program works fine. However, if I run it like this ./a.out < input.txt I get an infinite loop, regardless of the content of input.txt.
#include <iostream>
using namespace std;
int main() {
string input;
while (true) {
cout << "Type your input: ";
getline(cin, input);
cout << input << endl;
}
return 0;
}
What am I doing wrong?
EDIT: To clarify, I expect that after the input from the input file is finished, getline waits for more input from stdin. Instead, it continues to read when nothing is there.
You don’t have a terminating condition for your loop:
while (true)is an infinite loop in any case – that is, without a break/exit/etc. in the loop body.I’m guessing that when using your program to echo
stdinyou end it by pressing Ctrl-C. Run your program using./a.out, and type Ctrl-D (EOF): you’ll also get an infinite loop.Look over the docs for
getline: use the return value to end your loop: