Can't get char from cin.get()

Amir picture Amir · Sep 9, 2013 · Viewed 17.1k times · Source

I'm working through some beginner exercises on c++, and this has me stumped. I can enter a number, but I don't get the option to enter a character afterwards, and it skips to the final line.

I know I can use cin >> symbol, but i would like to know why this isn't working.

#include<iostream>
using namespace std;

int main() {

    cout << "Enter a number:\n";
    int number;
    cin >> number;

    char symbol;
    cout << "Enter a letter:\n";
    cin.get(symbol);

    cout << number << " " << symbol << endl;

    return 0;
}

Answer

awesoon picture awesoon · Sep 9, 2013

You should remove '\n' from stream, remained after entering the number:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Without it you will read newline character. You could check that with:

std::cout << (symbol == '\n') << std::endl;