Reputation: 1199
The code below should first prompt "Type a Letter: ". Once enter is pressed, the output should show "You typed: <achar>.
"
I'm using Jet Brains IDE, CLion. Yesterday the code worked as described above. Today, however, when I run the code, I get a blank line. If a key is pressed followed by enter, I get the output:
Letter: You typed: <achar>
If, however, I put a \n after "Type a letter: ", the prompt shows but outputs the pressed key on the next line because of the \n.
I've copied the exact code into a .c file, compiled and run it in Terminal and it runs as expected.
#include <stdio.h>
int main() {
int c;
printf("Type a letter: "); // works if \n used, but jumps to next line when key pressed
c = getchar();
printf("You typed: %c\n", c);
return (0);
}
Upvotes: 0
Views: 931
Reputation: 5307
It happens because after you type a letter and you hit ENTER you actually have your Letter (eg: A
) and the new line (\n
)character. This means that you need to clean the Buffer.
Try the following:
#include <stdio.h>
int main(void) {
int c;
printf("Type a letter: "); // works if \n used, but jumps to next line when key pressed
while((c = getchar()) != 0 && c != '\n' && c != EOF);
printf("You typed: %c\n", c);
return 0;
}
Upvotes: 0
Reputation: 8296
The terminal is buffered. printf("Type a letter: ");
if the printf contains a newline('\n'
) it is printed. Without a newline, you can force the printf by calling fflush(stdout);
otherwise the printf waits until the buffer is full before printing.
Be aware that input streams should NOT be flushed as fflush(stdin);
Upvotes: 3