2012-04-07 85 views
2

好的,我有這個任務,我必須提示用戶輸入關於5個獨立籃球運動員的數據。我的問題提示是在for循環中,循環執行第一次對第一個玩家罰款,但是當需要輸入第二個玩家信息時,前兩個問題提示一起在同一行,我已經擺弄這個,只是無法弄清楚,我相信這是我顯然缺少的東西,謝謝你有關如何解決這個問題的任何建議。for循環無法正確執行?

這裏是輸出:

Enter the name, number, and points scored for each of the 5 players. 
Enter the name of player # 1: Michael Jordan 
Enter the number of player # 1: 23 
Enter points scored for player # 1: 64 
Enter the name of player # 2: Enter the number of player # 2: <------- * questions 1 and 2 * 

這裏是我的代碼:

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


//struct of Basketball Player info 
struct BasketballPlayerInfo 
{ 
    string name; //player name 

    int playerNum, //player number 
     pointsScored; //points scored 

}; 

int main() 
{ 
    int index; //loop count 
    const int numPlayers = 5; //nuymber of players 
    BasketballPlayerInfo players[numPlayers]; //Array of players 

    //ask user for Basketball Player Info 
    cout << "Enter the name, number, and points scored for each of the 5 players.\n"; 

    for (index = 0; index < numPlayers; index++) 
    { 
     //collect player name 
     cout << "Enter the name of player # " << (index + 1); 
     cout << ": "; 
     getline(cin, players[index].name); 

     //collect players number 
     cout << "Enter the number of player # " << (index + 1); 
     cout << ": "; 
     cin >> players[index].playerNum; 

     //collect points scored 
     cout << "Enter points scored for player # " << (index + 1); 
     cout << ": "; 
     cin >> players[index].pointsScored; 
    } 

system("pause"); 
return 0; 

} 

回答

5

在閱讀的數字(例如,int),仍然有新的行留在輸入緩衝器你還沒看過。當您讀取另一個數字時,將跳過任何空格(包括換行符以查找數字)。但是,當您讀取一個字符串時,輸入緩衝區中的換行符被讀爲空字符串

要使其工作,您需要在嘗試讀取字符串之前從輸入緩衝區中取出新行。

+0

或者,您可以簡單地使用cin三次並完成它。getline總是在我看來,這是一個小小的錯誤 – Neil 2012-04-07 16:19:37

+1

@Neil:大概你的意思是使用操作符>>和'cin',在這種情況下,它不會工作 - 它只會讀取一個單詞,所以(用他的例子)當用戶進入「邁克爾喬丹」時,它會顯示爲「邁克爾」,但將「喬丹」留在輸入緩衝區中,然後程序會將其輸入嘗試讀取作爲球員號碼(顯然失敗)。 – 2012-04-07 16:22:13

+0

你顯然是對的,自從我在C++中編程基本輸入以來已經有一段時間了。 – Neil 2012-04-07 16:23:29