The problem here is that standard input (std::cin
) is buffered. So the program gets no input until the <return>
key is presses (or you fill the buffer). This gives you the impression that the code will always wait for user input.
This is not true. It will only wait for user input if the current buffer is empty. If there is data in the buffer it will read that rather than waiting for user input.
The first read:
cin.get(ch1);
Start of the program so the buffer is empty. So when you read from std::cin
the program will pause waiting for the buffer to be flushed then the characters will be read. If you hit A<return>
your buffer will flush with two characters in the buffer.
Buffer: 'A' '\n'
Your read will now retrieve thefirst character from the input: 'A'
leaving the '\n'
on the input stream:
Buffer: '\n'
Now the second read sees the buffer is not empty.
cin.get(ch2);
And does not need to wait it will read the next character from the stream. So it reads the '\n'
character from the stream. and continues.
Solutions:
That depends what you want. Do you want only the first character from the line?
std::cin.ignore(); // drops the rest of the line.
// The next character that will be available will
// be the first character of the next line.
You just want to ignore white space? (this is space/tab/newline etc).
std::cin >> v1 >> v2;
Using the operator>>
ignores leading white space, then reads the next value. So it will ignore new lines (they are white space).