Reputation: 87
int main()
{
int a;
a = getchar();
printf("%d", a);
}
output
10
This is When I wrote code like this and stroked only an 'enter' key on console. Keystroke 'enter' effect 1. put a '\n' in buffer 2. return that value to getchar sequently(It's what I am understanding about the situation). How can it possible? This result is like pressing enter key twice. I found a related question getchar, but I couldn't find something to help me understand.
Upvotes: 0
Views: 1159
Reputation: 15042
This result is like pressing enter key twice.
It is the behavior of getchar()
, when it encounters a newline character \n
only in stdin
, what makes the difference.
int main()
{
int a;
a = getchar();
printf("%d", a);
}
shows the appropriate output of:
10
when you input one "Enter" keystroke.
getchar()
waits for input until it encounters a newline \n
in stdin
then returns the character values until that moment; If \n
was the only character encountered, getchar()
stops scanning and returns this newline character and actually this is what was happen.
In this particular case, You do not need to push "Enter" a second time to affect that getchar()
stops scanning.
Upvotes: 2