Are they made changes to getchar() recently?

Why does these authors claim that getchar() acts in this way? Their book is from 2014. In its current version getchar() work just as expected - it read buffer's characters one by one. Have they made any change to this function recently - I doubt the aouthors are just an i$iots?!

https://drive.google.com/file/d/11CivXkVcz454OQnenSuJk6YBrnq0RB2i/view?usp=sharing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
int main()
{
	printf("What are your two initials?\n");
	char firstInit;
	char lastInit;

 	firstInit = getchar();
	lastInit = getchar();

	printf("first Init: %c \n", firstInit);
	printf("last init: %c \n",lastInit);
	return(0);
}
Last edited on
This program works as expected - and has always worked this way.

If you enter G<cr> T<cr> then firstInit gets the G and lastInit gets the <CR> - with T<cr> still in the buffer. If you enter GT <cr> then firstInit gets G and lastInit gets T with the <cr> still in the buffer. Note that getchar() only returns after a <cr> has been entered (easily proved by putting a puts("here"); after the first getchar() ).

However, the book discusses entering GT<cr> - hence it's incorrect (and always has been). It's not unusual for books (web sites et al) to be 'incorrect'.
Last edited on
There are numerous possible 'workarounds', including the one shown in the book. They all 'work'.

Trouble is none of them are any good without the prompt showing exactly how a user should enter the 2 initials.

Getting the user to enter a single string of 2 characters along with subsequent checking and processing would be better. After all that's what the stated purpose is.



"You would think that if the user typed GT, the G would go in the variable firstInit and the T
would go in lastInit, but that’s not what happens.
"

Probably they mean G<cr> T<cr> as you say - which is quite different from "if the user typed GT" but down in the text everything seems to speak only of an input type "G <cr> T<cr>". Tanks seeplus.
Topic archived. No new replies allowed.