我对编程比较陌生,我正在尝试使用Bjarne关于使用C ++的原理和实践的书中的一些代码。
我想知道为什么当输入不是整数时需要cin.unget()
而输入是整数时不需要cin.unget()
?
请注意,此代码并不完美,因为作者只是试图说明用户输入和输出的一些指针。代码如下:
void skip_to_int()
{
if (cin.fail()){
cin.clear();
for (char ch; cin>>ch; ) { // throw away non-digits
if (isdigit(ch) || ch=='-') {
cin.unget();
return;
}
}
}
error("no input");
}
int main(){
cout << "Please enter an integer in the range 1 to 10(inclusive):\n";
int n = 0;
while (true) {
if (cin>>n) { // we got an integer; now check it
if (1<=n && n<=10) break;
cout << "Sorry " << n
<< " is not in the [1:10] range; please try again\n";
}
else {
cout << "Sorry, that was not a number; please try again\n";
skip_to_int(); }
}
}
答案 0 :(得分:0)
它正在扫描您的输入流以查找数字或-
,这可能是负数字的一部分。这是剥离空格或标签之类的一种相当奇怪的方式。
unget()
的原因是将该字符推回到流中,以便稍后使用cin>>n
进行解析。如果你把它丢弃并把它扔掉,那就不可能了。