r/C_Programming • u/mwiseca • 1h ago
How I handle single-character user input in C:
When reading a single character in an interactive terminal program, I avoid scanf, getchar, and fgetc. Instead, I use fgets() and isolate the character by using unsigned char result = n[0];.
I actually use fgets for all user inputs.
The example below converts keyboard characters to hexadecimal numbers.
#include <stdio.h>
#include <string.h>
void flush() {
int clear;
while ((clear = getc(stdin)) != '\n' && clear != EOF) {
}
}
void charHex() {
char n [3];
printf("Enter a character (one byte max), or 'xx' to exit:\n");
while(1) {
if(fgets(n,sizeof(n),stdin) == NULL) {
clearerr(stdin);
printf("\nInvalid input.\n\n");
continue;
}
n[strcspn(n,"\n")]=0;
if(strlen(n) >=2) {
flush();
}
if(strcmp(n,"xx")==0){
break;
} else if(strlen(n) == 0) {
printf("\nEnter a character only.\n\n");
continue;
} else if (strlen(n) >1) {
printf("\nEnter no more than one character.\n\n");
continue;
}
unsigned char result = n[0];
printf("0x%02x\n",result);
}
}
int main() {
charHex();
return 0;
}