#include <stdio.h>
/* copy input to output */
main()
{
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}
return 0;
}
In the given code, the program displays the input character. It reads every character one by one (into the variable 'c') and outputs the same read characters simultaneously. The program terminates when the EOF character is given as input.
When I ran the code in my IDE (Code::Blocks 16.01) and input a string, eg: Hi! My name is C.\n
The output is displayed after '\n' and not simultaneously. Isn't the output supposed to be as - "HHii!! MMyy nnaammee iiss CC.."?
Bold letters indicate the output.
Because by default, input from terminal is line-buffered. So your program get a whole line after you press Enter.
To disable buffering in Unix & Linux systems, try this:
#include <unistd.h>
#include <termios.h>
int disableLineBuffer(void){
struct termios term, oldterm;
if (tcgetattr(STDIN_FILENO, &term)) return -1;
oldterm = term;
term.c_lflag &= ~(ECHO | ICANON);
if (tcsetattr(STDIN_FILENO, TCSANOW, &term)) return -1;
return 0;
}
In Windows, go and do this instead:
#include <windows.h>
BOOL WINAPI DisableLineBuffer(void){
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
if (!GetConsoleMode(hInput, &mode)) return FALSE;
mode &= ~ENABLE_LINE_INPUT;
if (!SetConsoleMode(hInput, mode)) return FALSE;
return TRUE;
}
Be sure to revert changes to the console before your program exits, or you may have trouble doing anything else in your terminal.