我正在學習C++,並且隨着我一起寫小程序。以下就是這樣一個程序:C++中的無限循環
// This program is intended to take any integer and convert to the
// corresponding signed char.
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(true){
std::cin >> n;
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
當我運行這個程序,並保持投入,在相當小的絕對值,其行爲與預期相同。但是,當我輸入較大的輸入時,例如10000000000,程序會反覆吐出相同的輸出。輸入的某些組合會導致不穩定的行爲。例如:
#: ./int2ch
10
10 -->
10000000000
10 -->
10 -->
10 -->
10 -->
該程序吐出「10 - >」直到它死亡。 (使用這種特定的輸入序列,程序的輸出速度變化速度不規律)。我還注意到,大值的輸出由前一個合法輸入以及當前非法輸入的值決定。
發生了什麼事? (我不在意修復這個程序,這很容易,我想理解它。)
或者,在std :: cin.clear()中引入一個調用,以在下一次循環之前刪除錯誤狀態。 – hark 2008-11-05 21:18:06