Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get char from cin.get()

Tags:

c++

cin

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;
}
like image 700
Amir Avatar asked Sep 09 '13 10:09

Amir


1 Answers

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;
like image 169
awesoon Avatar answered Sep 22 '22 07:09

awesoon