RetroFed Forum
Your home away from modern life.
[Help with C] Any way NOT to display the input of getchar() TWICE?
Post Reply
AuthorMessage
printf("%s", name); piefed.blahaj.zone akunohana@piefed.blahaj.zone
Joined: 2026-03-30
(edited) Quote

Goal: a program that takes a char as input and outputs which char has been inputted and the humber of line(s). The below code makes the program output the inputted char twice: once - I assume - as a result of how getchar() works and once as a result of printf(). Is there any way to do this more elegantly, as in, not displaying the inputted char twice? If possible, keep to while, without suggesting for.

PS: the repetition of getchar() is just my ugly way of removing the trailing '\n'.

#include <stdio.h>  

int main(void)  
{  
        int c, nl;  
        c = 0;  
        nl = 0;  

        while ((c = getchar()) != EOF) {  
                getchar();  
                printf("%c, %d\n", c, nl);  
                ++nl;  
        }  
}  
6   Original
mcmodknower programming.dev mcmodknower@programming.dev
Joined: 2023-07-22
#2 · Quote Reply

The first char appears because your terminal is echoing back what you are typing in.
This is the default, and you see it also in most other programs, with password inputs as a big exception. Those tell the terminal in some way that it should disable the echo functionality, and turn it back on after the password has been read.
see https://stackoverflow.com/questions/59922972/how-to-stop-echo-in-terminal-using-c for more info

6
printf("%s", name); piefed.blahaj.zone akunohana@piefed.blahaj.zone
Joined: 2026-03-30
#3 · Quote Reply

The first char appears because your terminal is echoing back what you are typing in. This is the default, and you see it also in most other programs, with password inputs as a big exception. Those tell the terminal in some way that it should disable the echo functionality, and turn it back on after the password has been read. see https://stackoverflow.com/questions/59922972/how-to-stop-echo-in-...

Nice! Thanks so much! :)

5
Post Reply
Back to top