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!
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:
readCharacter function;fflush(stdout) to flush the buffers after the printf call.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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With