Khanh Quoc Nguyen
Khanh Quoc Nguyen

Reputation: 49

Newline character is saved in stdin or not?

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?

Upvotes: 0

Views: 1500

Answers (2)

Ben Sivoravong
Ben Sivoravong

Reputation: 21

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.

Upvotes: 1

Revolver_Ocelot
Revolver_Ocelot

Reputation: 8785

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.

Upvotes: 0

Related Questions