Understanding getchar () in a C character counting program
This is the next question about my previous question. A similar question ( question ) has already been asked . But I don't understand what I want to know from this answer.
From the previous question, I learn that if I type a lot of characters, then they are not available for getchar () until I press Enter. So the moment I hit Enter, all characters will be available for getchar () s. Now consider the following program for counting characters:
#include<stdio.h>
main()
{
long nc;
nc=0;
while(getchar()!=EOF)
++nc;
printf(" Number of chars are %ld ",nc);
}
If I enter characters from the command line in the following sequence: {1,2,3, ^ Z, 4,5, Enter}, then on the next line {^ Z, Enter}. Expected result: Number of chars are 6
. But the output I get is Number of chars are 4
.
This answer explains that when we enter 1,2,3,^Z
then ^Z
acts like Enter
, and 1,2,3 are sent to getchar () s, the while loop of the above code is executed three times. ^Z
getchar () is not passed, so the program does not end yet. My input was {1,2,3, ^ Z, 4,5, Enter}. After ^ Z, I pressed 4.5 and then Enter. Now when I press Enter, the characters 4,5 and Enter must be passed to getchar () s and the while loop must run three times as long. Then on the last line I type {^ Z, Enter}, since there is no text behind ^ Z, it is treated as a character, and when I press Enter, that ^ Z is given as input to getchar () and the while loop ends. In all this, the while loop has executed 6 times, so the variable nc
should become 6
.
- Why am I getting
4
as valuenc
instead of6
.
source to share
Adding some result will help you:
#include <stdio.h>
int
main (void)
{
int c, nc = 0;
while ((c = getchar ()) != EOF)
{
++nc;
printf ("Character read: %02x\n", (unsigned) c);
}
printf ("Number of chars: %d\n", nc);
}
The Windows console views the input ^Z
as "send input up ^Z
to stdin, discards the remaining input on the line (including the end-of-line separator), and sends ^Z
" if it is not at the beginning of the line, in which case it sends EOF
instead ^Z
:
123^Z45
Character read: 31
Character read: 32
Character read: 33
Character read: 1a
^Z12345
Number of chars: 4
Also, Windows always waits for the Enter / Return key, except for very few key sequences such as ^C
or ^{Break}
.
source to share
^ Z or Ctrl-Z means end of file for text files (old MS-DOS). getchar () is equivalent to fgetc (stdin) and is often a macro. "fgetc returns a character read as int, or returns EOF to indicate an error or end of file."
See also _set_fmode, however I'm not sure if this will immediately change the behavior or if you need to close / reopen the file. Not sure if you can close / reopen stdin (don't do console programming anymore).
source to share