2013-03-05 56 views
0

確定,所以我嘗試學習C++,我是做一個模擬,但CIN不會爲我工作:(CIN不會工作

void Simulation::initialize(){ 
    cout<<"Choose number of players: " <<endl; 
    cin>> numberOfPlayer; 
    string name; 
    int accurasy; 
    int life; 
    for(int index=0; index <=numberOfPlayer;++index){ 
     cout<<"Enter name, accurasy and life for player"<<index +1 <<": " <<endl; 
     cin>>name; 
     cin>>accurasy; 
     cin>>life; 
     Kombatant comb(name,accurasy,life); 
     vect->push_back(comb); 

    } 
} 

這是不會工作的我的代碼。我試着玩家加入到仿真,一切工作正常,直到我獲得在for循環。出於某種原因,直到我到生活中,只能在第一個循環。然後,它跳過了生活的輸入之後,每一個輸入(每個輸入在所有的循環)。任何人有任何的想法是什麼問題?

+0

添加評論,如果你要我提供有關該計劃的任何其他信息 – 2013-03-05 12:28:03

+0

閱讀上如何CIN的作品,尤其是在混合輸入,因爲當你有字符串和整數時,cin會有點時髦。某些字符會留在輸入緩衝區中並導致您的行爲。它標記一個失敗位,然後導致程序退出。自從我觸摸C++之後已經有一段時間了,但我記得有同樣的問題。 – TheLazyChap 2013-03-05 12:30:35

回答

1

這是因爲最後的換行符仍處於輸入緩衝區。所以,當你循環名稱的輸入會看到newli ne並給你一個空的輸入。

你必須告訴輸入流中明確地跳過它:

// all your input... 

// Skip over the newline in the input buffer 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') 
+0

謝謝:)現在的工作。要閱讀該行的內容 – 2013-03-05 12:36:50