2013-01-07 42 views
2

我只是想用一個循環來填充字符串的數組。我的問題是,當它進入循環輸入名稱時,它會立即爲矢量中的第一個插槽輸入一個空行。爲什麼會發生?我該如何解決這個問題。請不要介意我缺乏的代碼風格,我想重新找回自己的編程知識之前,我在一類這個冬天開始小白......問題在一個循環中的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; 
} 
+6

選擇(HTTP [這一個]:// stackoverflow.com/search?q=%5Bc%2B%2B%5D+getline+skipping)。 – chris

回答

1

我可以建議你試試

std::cin >> names; 

,而不是

getline(std::cin, names); 

函數getline發生在std::endl\nstd::cout打印字符串。這個想法是,getline會一直讀取,直到\n字符(這是一個末尾的指示),但它也會消耗結束字符。這就是爲什麼它將消耗換行符到你的向量中。

請考慮這樣做。 。 。

std::cin.get(); 

這將讀取std::endl字符,然後使用getline函數。

+0

我想使用getline函數,以便您可以輸入完整的名字,包括第一個和最後一個。但是,這正是發生的事情。 –

+0

我忘記了,當我在換行符後使用getline時,我通常使用'std :: cin.get()'放棄換行符。 – rbtLong

+0

完美的工作!非常感謝!!! –

2

您看到此行爲的原因是將>>讀取與getline混合。讀取計數時,輸入指針會前進到數字輸入的末尾(即4),並在讀取新行字符之前停下。

這是當你撥打getline;新行字符被讀取,並且新行被立即返回。

要解決此問題,請在撥打cin >> number後立即添加對getline的呼叫,並放棄結果。

+0

Brillant!非常感謝。我想,也許你可以通過使用cin.clear()命令來清除cin函數中的任何內容(在本例中爲新行)? –

1

問題是混合輸入的輸入(std::cin >> number)與未格式化的輸入(std::getline(std::cin, names))。格式化的輸入停止在第一個非整數字符處,最有可能是您在計數之後輸入的換行符。最簡單的解決方法是跳過明確前導空格:

std::getline(std::cin >> std::ws, names); 

注意,你還需要每個輸入,這是成功後檢查:

if (std::cin >> number) { 
    // do something after a successful read 
}