【发布时间】:2018-07-24 21:06:53
【问题描述】:
我正在编写一个类似 shell 的解释器,使用 getchar() 进行缓冲输入。
- 如果按下
Enter,解释器应该处理缓冲区,然后提示换行。 - 如果按下
Ctrl+d,解释器应该处理缓冲区,然后退出。
下面的代码运行了,但不完全满足第二个要求。
#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;
}
我的问题是getchar() 仅在缓冲区为空时返回EOF。按Ctrl+d 中线会导致getchar() 返回每个缓冲的字符除了EOF 字符本身。
如何判断Ctrl+d是否被按下中线?
我考虑过使用超时。在此方法中,如果getchar() 在返回除换行符之外的其他内容后暂停太久,解释器将假定按下了Ctrl+d。这不是我最喜欢的方法,因为它需要线程化,引入了延迟,并且还不清楚适当的等待时间。
【问题讨论】:
-
正常行的末尾是
\n。使用 Ctrl+D 推动的行并非如此。 -
@Cheers:我如何确定不是
\n的字符是在行尾,还是行中还没有结束? -
你不能用stdio做这个,你需要使用低级输入函数。
-
stackoverflow.com/questions/7469139/… 解释了如何在不等待按下“Enter”的情况下读取字符
-
有没有跨平台的解决方案?