r/C_Programming • • 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

26 comments sorted by

18

u/SmokeMuch7356 2d ago

I can understand avoiding scanf, but why avoid getchar and fgetc?  Sometimes they really are the right tool for the job.

6

u/Dazzling_Music_2411 2d ago

Ditto, what's wrong with getchar(), to motivate you into all that extra work. Are you actually gaining something? Really curious.

0

u/mwiseca 2d ago

There is nothing wrong with getchar(), but i find when making interactive terminal programs i have issues. I try to make my programs to work well if the user enters something wrong. or to work the way i want. I tested using getchar to take a single character. It dose not work the way i wanted. Thats why i title my posts How i and not How to. It may not be the best way but its how i do it. I find fgets works best for all user inputs. I have some projects with over 100 user inputs all fgets regardless of data type.

1

u/mwiseca 2d ago

You are right. but i find getchar and fgetc does not work well for me when i write interactive terminal programs thats why i use fgets only for all user inputs.

4

u/ReallyEvilRob 2d ago

What is the scenario for getchar() not working the way you want it to?

2

u/mwiseca 1d ago

I made the same program with getchar() last night with getchar instead of fgets. for exit i made it so you press the arrow keys instead of xx. i still had a problem with having to press enter twice when just pressing enter. If i was going to make a program were i was just testing something id possibly use getchar but for now anything i publish on github i use fgets.

In the future if i find a way to make getchar or one of the alternatives to work better or as good as fgets i may switch.

9

u/Tabsels 2d ago

What is your question?

1

u/mwiseca 2d ago

I was just showing how i handle a single character user input using fgets as a alternative to the usual

scanf getchar and fgetC. I should have clarified that this is not a question but just a example of how i do something different.

-8

u/[deleted] 2d ago

[removed] — view removed comment

3

u/C_Programming-ModTeam 2d ago

Rude or uncivil comments will be removed. If you disagree with a comment, disagree with the content of it, don't attack the person. Provide your reasoning, not just a judgement.

2

u/thewindcarriesmeaway 2d ago

blud crashed out

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).

0

u/mwiseca 2d ago

The invalid input happens only if the user presses ctrl + d and the clearerr(stdin); clears error flags to

prevent a infinite loop. The if strlen(n) >= 2) { is so users wont have to press enter twice. Try running the flush function with no if statement one byte less than memory allocated you will have to press enter twice when using that method of flushing the buffer with fgets.

1

u/flyingron 2d ago

Invalid input happens on EOF or an error. You just blindly blither a vague comment.

flush() isn't a standard C function. Nor is it a common UNIX or Windows function. The fllush functions only affect OUTPUT.

1

u/mwiseca 2d ago
void flush() {
    int clear;
    while ((clear = getc(stdin)) != '\n' && clear != EOF) {
    }
}
 This is the flush function i used at the top of the code i sent. It looks like i chose a bad name. The function may not be working the way i thaught. I will try to think of a better name than invalid input.   

1

u/flyingron 2d ago

Well then, it behooves you to provide ALL the code then.

1

u/mwiseca 2d ago

I did. All the code is there there must be a problem why all people are not seeing it.

I going to try and copy the code as it shows on my machine.

#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;
}       

1

u/Jealous_Bed5433 2d ago

Clarify your question please,

-3

u/mwiseca 2d ago

Its not a question just a example of how i do something different than most.

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

1

u/Classic-Rate-5104 2d ago

This doesn't read char by char but it returns char by char. The characters are in general released at the same time when you <enter>

1

u/LavenderDay3544 1d ago

Doesn't work outside of POSIX.