The initial C book I'm reading confuses me with regards to getchar () and buffer order (especially with respect to the new line). It says:
Getting rid of the Enter key is a problem that all novice C programmers must face. Consider the following program segment:
printf("What are your two initials?\n"); firstInit = getchar(); lastInit = getchar();
You might think that if the user typed GT , G would fit in the firstInit variable, and T would fit in lastInit , but that is not what happens. The first getchar() does not end until the user presses Enter because G moved to the buffer. Only when the user presses Enter, G leaves the buffer and goes to the program & mdash, but then Enter is still in the buffer! So the second getchar() sends Enter ( \n ) to lastInit . T still remains for the next getchar() (if any).
Firstly, I donโt understand the authorโs explanation why \n goes to lastInit and not to T I think because I render the buffer as "first in first." In any case, I do not understand the ordering logic that the author presents: mdash, if the user enters G , then T , then Enter, how to do this so that G captured by the first getchar() , Enter (new line) is captured by the second getchar() , and T captured by the third getchar() ? Incomprehensible.
Secondly, I tried it myself (Ubuntu 14.04 runs on VMWare under Windows 8.1, the text editor Code :: Blocks, the gcc compiler), and I got the exact result of the general meaning, which the author says does not happen !: G goes to firstInit , and T goes into lastInit . Here is my code:
#include <stdio.h> main() { char firstInit; char lastInit; printf("What are your two initials?\n"); firstInit = getchar(); lastInit = getchar(); printf("Your first initial is '%c' and ", firstInit); printf("your last initial is '%c'.", lastInit); return 0; }
And the result:
What are your two initials?
GT
Your first initial is 'G' and your last initial is 'T'.
I also created the following program, which seems to confirm that a new line comes out of the last buffer:
main() { char firstInit; char lastInit; int newline; printf("What are your two initials?\n"); firstInit = getchar(); lastInit = getchar(); newline = getchar(); printf("Your first initial is '%c' and ", firstInit); printf("your last initial is '%c'.", lastInit); printf("\nNewline, ASCII %d, comes next.", newline); return 0; }
And the result:
What are your two initials?
GT
Your first initial is 'G' and your last initial is 'T'.
Newline, ASCII 10, comes next.
So am I missing something or is the author wrong? (or it depends on the compiler), although the author did not say that)?
Book: C Programming Absolute Guide for Beginners, 3rd Edition, Greg Perry, & copy; 2014, Ubuntu 14.04, gcc compiler version 4.8.4