2015-09-30 88 views
1

我遇到問題,我的for-loop跳過了getline函數。如果我用std :: cin代替它,那麼它就可以工作,所以我認爲它與我在getline中輸入的內容有關。For-Loop跳過getline C++

這是我的代碼。

void setLocations(int amount) { 
    locations = new std::string[amount]; 
    locations[0] = startingLocation; 

    // starts at 1 because we want to skip first index. The amount is set at 2 by default, so the loop should iterate at least once. 
    for (int x = 1; x < amount; x++) 
     std::getline(std::cin, locations[x]);  
} 
+9

http://stackoverflow.com/questions/6819082/stdgetline-on-stdcin – HelloWorld

+0

http://stackoverflow.com/questions/257091/how- do-i-flush-the-cin-buffer –

回答

2

可能是你在'setLocations'函數調用之前使用'std :: cin >> someVar',它不會消耗換行符。要解決問題,使用前該代碼段 'for' 循環

std::cin.ignore(1, '\n'); 
+0

我得到一個錯誤,它說我不能初始化int_type的一個參數,因爲它使用的是cin.ignore(1,「\ n」); –

+0

@Xari,抱歉,我的錯誤使用'\ n'而不是「\ n」。 – ashiquzzaman33