无法从cin.get()获得char [英] Can't get char from cin.get()
本文介绍了无法从cin.get()获得char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在通过c ++进行一些初学者练习,这让我很困惑。我可以输入数字,但是以后没有输入字符的选项,它会跳到最后一行。
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.
我知道我可以使用cin> >符号,但我想知道为什么它不起作用。
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;
}
推荐答案
第一个
将保留在缓冲区中。您可以通过在两次连续读取之间添加一个空的 cin
之后,n cin.get()
来解决此问题。
\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);
或者您可以使用 fflush
:
cin.get(string1,maxsize);
fflush(stdin);
cin.get(string2,maxsize);
这篇关于无法从cin.get()获得char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文