0

In my knowledge, when I write cin >> a command, program will wait user enter some characters until encounter newline character \n. That characters will be put into stdin. After that, cin will take fist character and put it into a variable.

I wrote this program to put 2 characters into stdin and use 2 cin commands get them to show:

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    char input;
    char input_next;
    cout << "Please enter a character from your keyboard: ";
    cin >> input;
    cout << input << endl;
    cin >> input_next;
    cout << input_next << endl;
    return 0;
}

Case 1: I enter string "KH" and press enter button. It show K and H.

Please enter a character from your keyboard: KH
K
H
Press <RETURN> to close this window...

Case 2: I enter character "K" and press enter button. It show K and wait I enter more character. It doesn't show newline character (enter button). Why?

2 Answers2

1

The ">>" operator skips all white space when reading in characters or strings. So, when you only input one letter, the program simply waits until you give it something to read in.

If you want it to read in newline characters, eof's, spaces, you can use the cin.get() function, which will get the next character in the buffer no matter what it is.

0

In my knowledge, when I write cin >> a command, program will wait user enter some characters until encounter newline character \n. That characters will be put into stdin.

It is slightly more complicated. C++ program interacts only with standard input stream. How characters ends in it, and how user can provide them to the program depends on OS (or maybe runtime library). Most OS do line buffering which has the behavior you described, but from the program point of view, it is fed a continuous stream of characters.

After that, cin will take fist character and put it into a variable.

It depends on type of a, but I suppose you meant that it has the char type. In this case it performs a formatted input: it discards all whitespace characters (space, tab, newline, vertical tab...) until it either encounters non-space or hits end of stream. You do not see newline printed, because operator>> skips it and waits for non-space character to appear in stream.

Revolver_Ocelot
  • 7,747
  • 3
  • 26
  • 45
  • That mean it will ignore whitespace characters, not considered whitespace is character like A,B,C,1,2,3... Right? – Khanh Quoc Nguyen Jul 16 '16 at 10:26
  • @khanhoct Yes. I suggets to check [reference](http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2). To read whitespace characters you can use [unformatted input](http://en.cppreference.com/w/cpp/io/basic_istream/get) – Revolver_Ocelot Jul 16 '16 at 10:34