J
Jules
I am trying to understand the behavior of a short program. Hopefully
someone can tell me what's going on.
The program I wrote is:
#include <stdio.h>
main()
{
char c;
while(1)
{
c=getchar();
printf("The character pressed was %c\n",c);
if(c=='q')
break;
}
}
I run it, and start pressing keys, and nothing happens. When I hit
return, I see a series of lines on the screen, one for each character
I pressed. If one of those keys is 'q,' the program does not exit
until I press return. I guess this means the input is being
buffered. Seems simple enough.
Next, I tried running the same program, piping the output to less.
Now, I don't see any of the output until the program exit, at which
point less displays the entire output. The funny thing here is that
the input is not buffered: As soon as I press q, the program
terminates and all of the output is displayed by less.
Can someone explain to me why the input is buffered in the first case
but not in the second? Also, if I want to get non-buffered input from
the keyboard, is there an easy way to do this? On my old computer, I
would use getch(), but I have learned that this is not standard, and
is not supported by the compiler I am using now.
someone can tell me what's going on.
The program I wrote is:
#include <stdio.h>
main()
{
char c;
while(1)
{
c=getchar();
printf("The character pressed was %c\n",c);
if(c=='q')
break;
}
}
I run it, and start pressing keys, and nothing happens. When I hit
return, I see a series of lines on the screen, one for each character
I pressed. If one of those keys is 'q,' the program does not exit
until I press return. I guess this means the input is being
buffered. Seems simple enough.
Next, I tried running the same program, piping the output to less.
Now, I don't see any of the output until the program exit, at which
point less displays the entire output. The funny thing here is that
the input is not buffered: As soon as I press q, the program
terminates and all of the output is displayed by less.
Can someone explain to me why the input is buffered in the first case
but not in the second? Also, if I want to get non-buffered input from
the keyboard, is there an easy way to do this? On my old computer, I
would use getch(), but I have learned that this is not standard, and
is not supported by the compiler I am using now.