I'm new to programming and learning C:
printf("What are your two initials?\n");
firstInit= getchar();
lastInit = getchar();
========================================
printf("What are your two initials?\n");
firstInit= getchar();
lastInit = getchar();
getchar();
I know that in the first section of code, if I type in ZK as initials, the Z will be placed in firstInit, and the '\n\ represented by the enter key will be placed into lastInit. The remaining K would be stored in a subsequent getchar(). However, in the second section of code, the book I'm reading said that if I type in ZK as initials, the firstInit will hold the Z, and the lastInit will hold the K. I just thought that the buffer needed to be cleared after each press of the enter key.
Sorry if this post is not allowed, will delete if needed.
There are two buffers are in action here: one is Keyboard buffer and another is C standard buffer (input buffer).
When you press the keyboard buttons then the characters stored in keyboard buffer. So when you type ZK
together then it simply stored at keyboard buffer. On pressing Enter key, it will goes to C standard buffer with one more character \n
(generated on pressing Enter key).
getchar
reads input character by character. In the first code, the first getchar
will read Z
into firstInit
and second getchar
will read K
into lastInit
. Now, only \n
is left in the input buffer.
The same is true for second code except that the \n
is read by third getchar
and is discarded.
If you press Enter key after each character Z
and K
, then you must have to clear input buffer after reading first character to store K
in lastInit
.