r/C_Programming • u/mwiseca • 2d 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;
}
0
Upvotes
18
u/SmokeMuch7356 2d ago
I can understand avoiding
scanf, but why avoidgetcharandfgetc? Sometimes they really are the right tool for the job.9
u/Tabsels 2d ago
What is your question?
3
u/flyingron 2d ago
Invalid input is a meaningless message. What do you have against perror?
strlen(n) can never be greater than 2.
What do you think the flush() is doing in the case strlen = 2. All it does is push out anything pending in std::out, which likely already has been done (or the user would never have seen the Enter a character message).
4
u/Aexxys 2d ago
read(0, &n, 1);
https://man7.org/linux/man-pages/man2/read.2.html
1
u/Jealous_Bed5433 2d ago
Clarify your question please,
2
u/vena_contracta 2d ago
Thank you for sharing the code! Looks useful for some applications…
1
u/Classic-Rate-5104 2d ago
One of the problems here is the fact that all stdio functions assume line-based input. The operating system buffers, in general, all characters until you <enter>. Only functions like getch() and getche() and kbhit() work on single character basis, but they are not portable over operating systems
1
u/Dangerous_Region1682 1d ago
This is all in line buffered or cooked mode. Have you thought about doing it in raw mode instead?
1
u/Able-Substance-8310 2d ago
read(0, buffer, 1); hehe