darklord
darklord

Reputation: 5167

why cin.get only wait for user input once

I am expecting the following program to stop twice for waiting my input characters. The first time it stops and wait me to type a character, I typed a character and press enter, however the console doesn't wait me to input 'char c' after that, it just end and prints out only what I typed for 'char b'. Why is that?

    #include <iostream>

    using namespace std;

    int main() {
        char b;
        cin.get(b);
        char c;
        cin.get(c);
        cout << b << c << endl;
    }

Upvotes: 0

Views: 1046

Answers (2)

rflobao
rflobao

Reputation: 597

Use:

char b;
cin >> b;
char c;
cin >> c;
cout << b << c << endl;

Upvotes: 1

Sam Varshavchik
Sam Varshavchik

Reputation: 118300

The question states:

1) Some key on the keyboard was pressed.

2) Another key on the keyboard labeled "Enter" was pressed.

Pop quiz: how many characters were typed?

Answer: two characters were typed.

The first get() reads the first character. The second get() reads the second character, the Enter key.(*)

(*) The above answer assumes a non-multibyte locale.

Upvotes: 3

Related Questions