0
我對編程相對比較陌生,我正在試驗Bjarne的一些關於使用C++的原理和實踐的代碼。爲什麼在這個上下文中需要cin.unget(),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(); }
}
}