I'm writing a shell-like interpreter using getchar() for buffered input.
- If
Enteris pressed, the interpreter should process the buffer, then prompt for a new line. - If
Ctrl+dis pressed, the interpreter should process the buffer, then exit.
The code below runs, but does not fully satisfy the second requirement.
#include <iostream>
using namespace std;
void shell() {
for (int input;;) {
// prompt at beginning of line
std::cout << ">>> ";
while ((input = getchar()) != '\n') {
// still in current line
if (input == EOF) {
// ctrl+d pressed at beginning of line
return;
}
std::cout << "[" << (char)input << "]";
}
// reached end of line
}
}
int main() {
cout << "before shell" << endl;
shell();
cout << "shell has exited" << endl;
return 0;
}
My issue is getchar() only returns EOF when the buffer is empty. Pressing Ctrl+d mid-line causes getchar() to return each buffered character except the EOF character itself.
How can I determine if Ctrl+d is pressed mid-line?
I've considered using a timeout. In this method, the interpreter assumes Ctrl+d was pressed if getchar() halts for too long after returning something other than a line feed. This is not my favorite approach because it requires threading, introduces latency, and the appropriate waiting period is unclear.