Here, I have understood why putchar() is printing only the first character that is 'C'
#include <stdio.h>
main(){
int c;
c = getchar();
putchar(c);
}
output : > Cprograming
> C
But, When using a while loop the behavior of those functions is changing.
#include <stdio.h>
main(){
int c;
c = getchar();
while(c != 2){
putchar(c);
c = getchar();
}
}
output : > Cprograming
> Cprograming
> Bells and Wistles
> Bells and Wistles
...
Why suddenly getchar() and putchar() are storing and printing more than one character..?? Why is this happening..??
I tried to practice it this way.
int c,d,e,f,g;
c = getchar();
putchar(c);
d = getchar();
putchar(d);
e = getchar();
putchar(e);
f = getchar();
putchar(f);
g = getchar();
putchar(g);
This is my assumption how program might be working.
Start with c = getchar()
User enter 'Qwerty'
getchar() stores this 'Qwerty' one by one character in something called input buffer(sorry for technical words)
user hits enter, getchar() returns the first character from buffer and store it into c
putchar(c), sends this value to something called output buffer, Now output buffer has Q stored in it . Next, d = getchar(), now this new getchar(), goes to the input buffer asks for the top character stored in it and return it to 'd'
putchar(d), sends this new d value to output buffer, and now output buffer contains 'Qw'
--this repeats until we don't have enough getchar() & putchar() or we run out of characters.
In this case, we don't have enough getchar() & putchar(). So, the output screen will look something like this
Qwerty
Qwert
My question is,
Why d = getchar(); collects character from buffer. Why it does not just start a new stream for itself...?
I mean c = getchar(); says ok start typing
and
d = getchar(); No, don't start typing. first check if buffer has something left. if it doesn't only then start typing.
Why..?
I'm really sorry if I'm being absolutely silly. Just a beginner programmer. Hope you guys understand.