What makes getch inherently unportable to be included as a standard C function?
It is so intuitive and elegant for console interfaces. Without it, asking for a single character is always misleading because users are allowed to enter more than one key.
Worse, you are often required to make sure to clear standard input after reading console input, which isn't even provided as a standard feature! I have to use my own!
A simple program which could be:
#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;
}
Every time I want to make a simple portable console program, I feel forced into making a bunch of functions like that, and still end up not having all the things I want, like getch.
Sure, you could use curses, but curses takes over your whole console, and makes your program behave differently than what a regular user expects(for the program to just scroll, and still show the command you ran the program with in the console buffer).
I know "why" is a bad question(what should always be prefered), but it must be asked. Is there anything inherently unportable in getch that a desktop system can't support? If there isn't, I can just write my own and port it to all the platforms I want to support and I'm good.
If there is something getch does that can't be supported by a desktop system, what is it? So I have better reason for understanding why conio is avoided than "just use ncurses/conio is not standard".