Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf done after getchar, while being placed before [duplicate]

Tags:

c

eclipse

Okay so i'm trying to make a "read character" function that would only take upper or lower-case letters, not accents (i'm french so it's important with french keybords) and return it upper-cased. For that i made another source file for the readcharacter function:

char readCharacter()
{
    char character;

    do
    {
        printf("Please enter a letter without accents and hit 'enter': ");

        character = getchar();
        while(getchar() != '\n');

        printf("\n");

        character = toupper(character); //Upper-case if lower case
    } while(((character < 65)||(character > 90)));
    return character;
}

Here's my main:

#include "main.h"
int main(void)
{
    char MyLetter = readCharacter();
    char MyLetter2 = readCharacter();
    printf("%c\n%c\n", MyLetter, MyLetter2);
}

My problem is, i got this as output:

S
l
Please enter a letter without accents and hit 'enter': 
Please enter a letter without accents and hit 'enter':
S
L

Why don't i get this?

Please enter a letter without accents and hit 'enter':S 
Please enter a letter without accents and hit 'enter':l
S
L

Don't know if this is relevant, but my IDE is eclipse and compiler is MinGW (gcc?) Sorry for bad english and/or bad coding... i've just started coding... Thx!

like image 443
Jules Raschilas Avatar asked Feb 26 '26 23:02

Jules Raschilas


2 Answers

The problem is that output to stdout (which is used by printf) is line buffered by default. That means the buffered output is only written if there's a newline, the buffer gets full or you explicitly flush it.

Since none of that happens here in your function, the output is simply "delayed" until it is flushed by the newline you print in the main function.

There are two solutions:

  1. Either add a newline at the end of the string you print in the readCharacter function;
  2. Or call fflush(stdout) to flush the buffers after the printf call.
like image 135
Some programmer dude Avatar answered Feb 28 '26 13:02

Some programmer dude


You need to be careful with interactive programs that do not print \n, because the output may remain buffered for longer than you need.

Add a call to fflush(stdout) after printf, or add \n at the end of the string that you print to fix this problem.

Note that pressing Ctrl+D (Ctrl+Z on Windows) turns the loop that waits for '\n' while(getchar() != '\n'); into an infinite loop.

Also note that you can avoid numeric comparisons to character codes, such as character < 65, by using !isupper(character).

like image 29
Sergey Kalinichenko Avatar answered Feb 28 '26 11:02

Sergey Kalinichenko