Getchar and putchar

My C code:

int c; c = getchar(); while (c != EOF) { putchar(c); c = getchar(); } 

Why does this program react like that when you type hello ?

 hello hello 

and do not like:

 hheelloo 
+4
source share
6 answers

Your input is hello , not h e l l o right?

Thus, the input you enter is buffered until you press enter .

+5
source

When you type, the console captures the output from the keyboard, repeating it back.

getchar() runs on the input stream, which is usually configured with "Canonical input" enabled. This configuration reduces the processor’s time spent polling input for a buffering scheme where the input is buffered until certain events occur that signal buffer expansion. Pressing the enter key (and control D) flushes this buffer.

 #include <unistd.h> int main(void){ int c; static struct termios oldt; static struct termios newt; /* Fetch the old io attributes */ tcgetattr( STDIN_FILENO, &oldt); /* copy the attributes (to permit restoration) */ newt = oldt; /* Toggle canonical mode */ newt.c_lflag &= ~(ICANON); /* apply the new attributes with canonical mode off */ tcsetattr( STDIN_FILENO, TCSANOW, &newt); /* echo output */ while((c=getchar()) != EOF) { putchar(c); fflush(STDOUT_FILENO); } /* restore the old io attributes */ tcsetattr( STDIN_FILENO, TCSANOW, &oldt); return 0; } 
+4
source

Your terminal probably only writes your input to stdin when you press enter. Try typing something, come back and write something else; if you do not see the characters you originally entered, this means that your terminal expects you to make a string before sending data to the program.

If you want to access the source terminal (for example, to respond to keystrokes and keystrokes), try using some terminal library like ncurses .

+3
source

Standard input / output streams can be buffered, which means that your input may not be displayed on the screen until a space character is encountered (for example).

+1
source

Since the default value for stdin , when it refers to the keyboard, should be buffered in a line.
This means that you only see complete lines, not single characters.

Imagine asking your friend what his phone number is ... but he should write it down on a piece of paper. You don’t get digit by digit, as he writes them: you get the whole number when he gives you a piece of paper :)

+1
source

getchar reads the input stream, available only after pressing the ENTER key. until then you only see the echo result from the console. To achieve the result you want, you can use something like this

 #include <stdio.h> #include <termios.h> #include <unistd.h> int getCHAR( ) { struct termios oldt, newt; int ch; tcgetattr( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); putchar(ch); tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); return ch; } void main() { int c; c = getCHAR(); while (c != 'b') { putchar(c); c = getCHAR(); } } 
0
source

All Articles