When i try the loop, i find some doubts.
When i press "Enter" first time, it prints two blank lines, at the second time, it prints two more blank lines and execution following statement.
When i press "Enter" then "#", and "Enter" again it won't end.
I wonder why?
while((ch = getchar()) != '#')
{
putchar(ch);
while(getchar() != '\n')
;
printf("\nEnter next word.");
}
i want to understand how it works.
As suggested in the comments, I recommend using a debugger to step through this program. Seeing what is happening line by line is the best way to understand eveything that is happening and improve your coding skills.
That said it will help to have some knowledge of what getchar
is doing by default when you have an interactive program on most systems. When you call getchar
the first time it will in turn call a lower level operarating system function which will get input from the standard input (stdin
). On linux for example the low level function is read
which will get input from a terminal.
On most systems what will happen by default is that the low level function won't return until enter is pressed. Anything typed will also be echoed back to the terminal/console, so you will see what you are typing.
Once you press enter getchar
will return the first character relating to what you typed. If you type more than one character, the your next call to getchar
will return immediately with the next chatacter you typed. Note that on Linux when you hit enter, it will be like you typed '\n'
, however on Windows line endings are different, so it will be like '\r'
then '\n'
.
So the reason you see 2 blank lines the first time you hit enter is because the first is being echoed back by your low level os function, then the second by your putchar
. getchar
is called again and your 3rd blank line comes from the echo. The fourth comes from your printf
.
I will leave the second part for you to figure out on your own.