2016-11-26 260 views
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(); } 
    } 
} 

回答

0

這是通過掃描你的輸入流中找到數字或-這是一個負的數字的一部分,大概。這是一種非常好奇的方式來剝離空間或製表符之類的東西。

unget()的原因是將該字符推回到流中,以便以後可以使用cin>>n進行解析。如果你把它消耗掉了,那就不可能在那個時候提供。

相關問題