Question

When I do practice on K&R,I found a very interesting question:

code as follows:


include <stdio.h>
main()                                                                                              
{                                                                                                   
    int c;
    int bn;
    bn=0;
    while((c=getchar())!=EOF)                                                                       
    {                                                                                               
        if(c==' ')                                                                                  
        bn++;                                                                                   
    }                                                                                           
    printf("blanks counter:%d\n",bn);                                                               
} 

code function is number of statistical blankspaces

I enter all the words at once ,no use backspace key,it is done.


$ ./a.out

I have a dream

blanks counter:3

however,if I use backspace key,what happen may be in input process?

I speculate when a blankspace key is pressed ,getchar() function should get this event,and then perform bn++ ,so even if I later press a backspace key to delete this blankspace ,the value of bn variable is not change. but the result of practice is different of my speculate, the programe of practice as follows:

the first step:input first blankspace enter image description here

the second step:use backspace key delete thie blankspace enter image description here the third step:finish the remaining input of characters enter image description here

why result is 3 not 4?why value of bn variable would be changed by pressed backspace key?

please give me some ideas,thanks!

Was it helpful?

Solution

Your console is line buffering stdin. This means that your program will not receive any input until you hit Return, and it will receive the edited text, not the actual sequence of keystrokes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top