dbconfession dbconfession - 1 year ago 131
C Question

C getchar() works properly in terminal but not CLion

The code below should first prompt "Type a Letter: ". Once enter is pressed, the output should show "You typed:


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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download