c - why I must to call the `getchar()` additional? -
/* c89 */ #include<stdio.h> int main(void){ int c; printf("print not eof char: "); c = getchar(); /* set char , press come in key here.*/ printf("int value: %d\n", c); printf("now print eof char \n(ctrl + z windows, " "or ctrl + d linux): "); c = getchar(); eof == c ? printf("you did it! int value: %d\n", c) : printf("it not eof char!\n"); homecoming 0; }
when press 'a' key , press enter, this: output:
print not eof char: int value: 97 print eof char (ctrl + z windows, or ctrl + d linux): not eof char!
so not asked me char in sec phone call of getchar(). why?
if press 'a' char , ctrl + z (i utilize windows os), this: output:
print not eof char: a^z int value: 97 print eof char (ctrl + z windows, or ctrl + d linux): not eof char!
but ctrl + z eof windows os. why happened?
if modify code:
/* c89 */ #include<stdio.h> int main(void){ int c; printf("print not eof char: "); c = getchar(); /* set char , press come in key here.*/ printf("int value: %d\n", c); printf("now print eof char \n(ctrl + z windows, " "or ctrl + d linux): "); getchar(); /* ignore come in key pressed before. */ c = getchar(); /* can inquire next char. */ eof == c ? printf("you did it! int value: %d\n", c) : printf("it not eof char!\n"); homecoming 0; }
now output expected: output:
print not eof char: int value: 97 print eof char (ctrl + z windows, or ctrl + d linux): ^z did it! int value: -1
why happened? i.e. why must phone call getchar()
additional?
pressing come in key 2 things: adds newline character (ascii nl, code 10) @ end of input buffer , flushes it, making whole line available getchar()
. after pressing 'a' need press come in also, programme can see , interpret 'a'. must skip nl character input stream additional getchar()
.
however know next request be, can press 'a' (entering 'a'), ctrl+z (entering eof character) , come in (entering nl , sending 3 characters processing) – 2 characters 'a' , eof read 2 getchar
s.
c
No comments:
Post a Comment