我只是想用一個循環來填充字符串的數組。我的問題是,當它進入循環輸入名稱時,它會立即爲矢量中的第一個插槽輸入一個空行。爲什麼會發生?我該如何解決這個問題。請不要介意我缺乏的代碼風格,我想重新找回自己的編程知識之前,我在一類這個冬天開始小白......問題在一個循環中的cin函數
下面是一些示例輸出:
How many people are in your family?
4
Please enter the names of all of your family members
check name:
Please enter the names of all of your family members
Matt
check name:Matt
Please enter the names of all of your family members
Evan
check name:Evan
Please enter the names of all of your family members
Michelle
check name:Michelle
Matt
Evan
Michelle
這是我的代碼:
vector<string> Names;
bool complete=0;
while(!complete)
{
int number;
cout << "How many people are in your family?" << endl;
cin >> number;
for(int i=0; i<number; i++)
{
string names;
cin.clear();
cout << "Please enter the names of all of your family members" << endl;
getline(cin,names);
Names.push_back(names);
cout << "check name:" << names << endl;
}
complete = 1;
}
for (int i=0; i< Names.size(); i++)
{
cout << Names[i] << endl;
}
選擇(HTTP [這一個]:// stackoverflow.com/search?q=%5Bc%2B%2B%5D+getline+skipping)。 – chris