是什么使得 getch 本质上无法作为标准 C 函数包含在内?
对于控制台界面来说,它是如此直观和优雅。如果没有它,要求输入单个字符总是会产生误导,因为用户可以输入多个键。
更糟糕的是,您经常需要确保在读取控制台输入后清除标准输入,这甚至不是作为标准功能提供的!我得用我自己的!
一个简单的程序可以是:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
int main(int argc, char **argv)
{
while (1) {
char yes_or_no;
printf("is this statement correct? 1 + 1 = 2(Y/N) $ ");
yes_or_no = tolower(getch());
switch (yes_or_no) {
case 'y':
puts("Right!");
goto done;
case 'n':
puts("\nhint> Please just say yes for the sake of this demo...");
break;
case 'q':
puts("\nExitting.");
goto done;
case EOF:
puts("\nEOF.");
goto done;
default:
printf("\nunknown response '%c'.\n", yes_or_no);
break;
}
}
done:
return 0;
}
becomes:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
static inline void flush_stdin()
{
char ch;
do {
ch = getchar();
} while ((ch != '\n') && (ch != EOF));
}
int main(int argc, char **argv)
{
while (1) {
char yes_or_no;
printf("is this statement correct? 1 + 1 = 2(Y/N) $ ");
yes_or_no = tolower(getchar());
switch (yes_or_no) {
case 'y':
puts("Right!");
goto done;
case 'n':
puts("hint> Please just say yes for the sake of this demo...");
break;
case EOF:
puts("EOF.");
goto done;
default:
printf("unknown response '%c'.\n", yes_or_no);
break;
}
flush_stdin(); /* remove this to see the difference */
}
done:
return 0;
}
每次我想要制作一个简单的便携式控制台程序时,我都会觉得被迫制作一堆类似的功能,但最终仍然没有得到我想要的所有东西,比如 getch。
当然,您可以使用curses,但是curses接管您的整个控制台,并使您的程序的行为与普通用户期望的不同(程序只是滚动,并且仍然在控制台缓冲区中显示您运行程序的命令) 。
我知道“为什么”是一个坏问题(什么应该始终是首选),但必须问。 getch 中有什么本质上不可移植的东西吗?desktop系统不支持?如果没有,我可以自己编写并将其移植到我想要支持的所有平台上,这样就很好。
如果 getch 所做的某些事情无法得到支持desktop系统,是什么?因此,我有更好的理由理解为什么避免使用 conio,而不是“仅使用 ncurses/conio 不是标准”。