无法从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);