2014-10-31 62 views
0

我已經編程了一段時間(在Prolog,Scheme和C中有一點點),但我最近決定刷新我的C++知識。我解決了一個旨在說明向量的問題。它本質上是一個創建數據庫的項目,該數據庫創建一個矢量,臨時存儲用戶輸入的各種遊戲,並刪除他們不想要的遊戲。代碼本身運行良好,不像程序或Prolog可以做到的那樣漂亮,但它工作正常。爲什麼控制+ P導致C++(Visual Studio)中的無限循環?

然而,我不小心鍵入「控制P」到程序的第一個提示,我得到了奇怪的結果:它開始一個無限循環。我再次嘗試「控制Z」我得到了同樣的結果。我還沒有嘗試過任何其他關鍵組合,但我想像其他人可以找到。這不是一個令人擔憂的問題,但我很想知道爲什麼這樣做。是關於C++的東西,還是僅僅是Visual Studio?總之,這裏的源:

#include <iostream> 
#include <string> 
#include <vector> 
using namespace std; 

int main() 
{ 
cout << "Welcome to the Cpp Games Database!"; 

int x = 0; 
string game = ""; 
vector <string> games; 
vector <string>::const_iterator iter; 
while (x != 4){ 
    cout<< "\n\nPlease choose from the list bellow to decide what you want to do:\n"; 
    cout<< "1. Add Games to the Database.\n" 
     << "2. Remove Games from the Database.\n" 
     << "3. List all the Games.\n" 
     << "4. Exit.\n" 
     << "\n(Type the number of your choice and hit return)\n"; 
    cin >> x; 
    switch (x){ 
     case 1: 
      game = ""; 
      do{ 
       cout << "\nPlease Input a Game (type esc to exit): "; 
       cin >> game; 
       games.push_back(game); 
      } while (game != "esc"); 
      games.pop_back(); 
      break; 

     case 2: 
      game = ""; 
      do{ 
       cout << "\nPlease input the game you would like to remove(or type esc to exit): "; 
       cin >> game; 
       iter = find(games.begin(), games.end(), game); 
       if(iter != games.end()) 
        games.erase(iter); 
       else cout << "\nGame not found, try again please.\n"; 
      } while (game != "esc"); 
      break; 

     case 3: 
      cout << "\nYour Games are:\n"; 
      for (iter = games.begin(); iter != games.end(); iter++) 
      { 
       cout << endl << *iter << endl; 
      } 
      break; 
     default: break; 
    } 
} 
return 0; 
} 
+1

您拒絕檢查您的I/O操作的返回值,現在您要支付價格。 – 2014-10-31 03:18:21

回答

0

既然你沒有爲cin這是卡在那裏等待的數據進行再處理或丟棄新的輸入輸入有效的數據。你需要檢查你的輸入,只接受有效的數據。本質上cin保持它給出的原始數據並不斷嘗試處理它。

請務必驗證您的輸入,如果無效,請將其丟棄。

下面是關於同一問題的另一個答案,以獲得更多的見解(與源代碼)。 https://stackoverflow.com/a/17430697/1858323

+0

第一部分是正確的,但編譯器改變數值或更糟的想法很奇怪。這是指什麼價值?編譯器如何影響運行時問題,該問題目前沒有運行? – MSalters 2014-10-31 07:52:09

+0

編譯器不在運行時進行更改。不同版本的不同編譯器將對無效數據產生不同的影響,例如將值更改爲0並設置失敗位。此行爲在編譯期間根據版本等因素設置。但是,有些只會進入失敗狀態並繼續循環。請參閱上面給原始答案的鏈接。 – Eric 2014-10-31 17:23:29

相關問題