I think this is a great question with many applications! For this, termios.h is better than curses.h in my opinion because with termios.h you can input to the terminal as you normally would, without requiring a fullscreen application like curses seems to. Also, you do not need to compile with a library (curses requires -lcurses
option in your compiler). Note that this solution requires you to implement your own getch
-like function. In addition, this solution is linux specific (AFAIK)
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <locale.h>
#include <wchar.h>
wint_t mygetwch()
{
// Save the current terminal details
struct termios echo_allowed;
tcgetattr(STDIN_FILENO, &echo_allowed);
/* Change the terminal to disallow echoing - we don't
want to see anything that we don't explicitly allow. */
struct termios echo_disallowed = echo_allowed;
echo_disallowed.c_lflag &= ~(ICANON|ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &echo_disallowed);
// Get a wide character from keyboard
wint_t wc = getwchar();
// Allow echoing again
tcsetattr(STDIN_FILENO, TCSANOW, &echo_allowed);
// Return the captured character
return wc;
}
int main()
{
// Imbue the locale so unicode has a chance to work correctly
setlocale(LC_ALL, "");
// Start endless loop to capture keyboard input
while (1) {
wint_t wc = mygetwch(); // get a wide character from stdin
if (wc==WEOF) // exit if that character is WEOF
break;
else if (wc==L'\\') // replace all instances of \ with λ
wprintf(L"%lc",L'λ');
else // otherwise just print the character
wprintf(L"%lc",wc);
}
return 0;
}