I can't actually seem to find it written anywhere in the docs, but the extraction operator (<<
) ignores leading whitespace and reads as many characters as it can until it finds a whitespace character.
Edit:
Looks like the cppreference page for the extraction operator actually does specify the behaviour with regard to whitespace: "After constructing and checking the sentry object, which may skip leading whitespace, extracts a character and stores it"
So for you, the space and newline get eaten and the extraction operator continues waiting, since it hasn't read any non-whitespace characters.
If you want to read a single character (whitespace or not), use get
. ie:
char ch;
cout << "Enter the character: ";
cin.get(ch); //can also be called ch = cin.get();
cout << "ASCII code is: " << static_cast<int>(ch) << endl;
(also as an aside--since this is c++, you should be using static_cast
instead of c-style casting. See my code above for an example)