2009-12-24 30 views
2

如果輸入字符串,下面的函數將導致無限循環使用C++ IO istream讀取的對象導致無限循環

istream & inputFunc(istream &is) 
{ 
    int ival; 
    // read cin and test only for EOF; loop is executed even if there are other IO failures 
    while (cin >> ival, !cin.eof()) { 
     if (cin.bad())   // input stream is corrupted; bail out 
      throw runtime_error("IO stream corrupted"); 
     if (cin.fail()) {      // bad input 
      cerr<< "bad data, try again";  // warn the user 
      cin.clear(istream::failbit);   // reset the stream 
      continue;       // get next input 
     } 
     // ok to process ival 
     cout << "you entered: " << ival << endl; 
    } 



} 

無限循環的以下功能的結果,如果一個字符串被輸入作爲輸入。

輸出

嘗試againbad數據,嘗試againbad數據,嘗試againbad數據,嘗試againbad數據,嘗試againbad數據,嘗試againbad數據,嘗試againbad數據,嘗試againbad數據,嘗試againbad數據,嘗試再次嘗試數據,嘗試再次嘗試數據,嘗試再次嘗試數據,嘗試再次嘗試數據,嘗試再次嘗試數據,嘗試再次嘗試數據,嘗試再次嘗試數據,嘗試再次嘗試數據,嘗試再次嘗試數據,嘗試再次嘗試數據,嘗試再次嘗試數據,嘗試再次嘗試數據,

+0

你如何發送EOF信號到你的程序? – rui 2009-12-24 09:21:41

回答

1

你需要做兩件事情:

1)明確的狀態就像這裏:清除狀態後cin.clear(istream::goodbit);

2)跳過一個字符的時間,因爲你不知道下一個數開始:

char c; 
cin >> c; 
+0

謝謝,現在工作。 – aehjaj 2009-12-24 09:28:21

0

是的,它無限循環。看看cin.clear()。

0

錯誤的數據仍然位於輸入流中嗎?如果是這樣,這樣的事情可能會有所幫助:

if (cin.fail()) {      // bad input 
     string badData;      // create a string to hold the bad input 
     cin.clear(istream::failbit);   // reset the stream 
     cin >> badData;      // read the bad input to clear the stream 
     cerr<< "bad data: " << badData << ", try again"; // warn the user 
     continue;       // get next input 
    }