Buffering in getchar()

Buffering in getchar() doesnt always work the way you would expect.

#include <stdio.h>
#include <unistd.h>
#include <termios.h>

int main()
	char x = ' ';
	printf("Press any key to continue...\n");
	x = getch();
	printf("The key you entered is: %c \n", x);
	return 0;

int getch(void)
	int ch;
	struct termios oldt;
	struct termios newt;
	tcgetattr(STDIN_FILENO, &oldt);
	newt = oldt;
	newt.c_lflag &= ~(ICANON | ECHO); /* Turn off line buffering and echo */
	tcsetattr(STDIN_FILENO, TCSANOW, &newt);
	ch = getchar();
	tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
	return ch;

Leave a Reply

Your email address will not be published. Required fields are marked *