Can't get char from cin.get()

偶尔善良 提交于 2020-02-21 11:53:12

问题


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;
}

回答1:


\n will remain in the buffer after the first cin. You can solve this problem by adding an empty cin.get() between two consecutive reads.

cin.get(string1,maxsize);
cin.get();
cin.get(string2,maxsize);

Or you can use fflush:

cin.get(string1,maxsize);
fflush(stdin);
cin.get(string2,maxsize);



回答2:


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;


来源:https://stackoverflow.com/questions/18696531/cant-get-char-from-cin-get

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!