2015-04-23 80 views

回答

3

你叫第二次getline你實際上是在閱讀一個換行符,因爲cin >>不丟棄換行符後的值它剛剛讀取。

所以你最終在這個閱讀不良數據的週期。試試這個:

getline(cin >> std::ws, names[i]); 
+0

謝謝你的工作。 ws做什麼? – user3462406

+1

@ user3462406,http://en.cppreference.com/w/cpp/io/manip/ws – chris

+1

@ user3462406:'std :: cin >> std :: ws'會吃掉所有的空白字符(換行符,製表符,空格),有效地將該流引導至下一個非空白字符以供閱讀。 – AndyG

1
cin >> earnings[i]; 

這應該更正如下

getline(cin, earnings[i]) 

//示例程序

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

int main() 
{ 
    string names[10]; 
    string earnings[10]; 
    for (int i = 0; i< 10; i++) 
{ 
    cout << "Enter the name of the movie: "; 
    getline(cin, names[i]); 

    cout << "How much did " << names[i] << " earn <in millions>: "; 
    getline(cin, earnings[i]); 
    cout << endl; 
} 
cout<< names[0]<< names[1]<<"\n"; 
cout<<earnings[0] << earnings[1]<<"\n"; 
return 0; 

} 
+1

收益是一個雙數組,對不起。我忘了提到這一點。 – user3462406

1

的問題是,>>不讀過去的行結束所以下面的std::getline()這樣做,而不是抓住你的下一個輸入。

您可以使用std::ws(吸收空格字符):

for (int i = 0; i< NUM_MOVIES; i++) 
{ 
    cin >> std::ws; // clear previous line 

    cout << "Enter the name of the movie: "; 
    getline(cin, names[i]); 

    cout << "How much did " << names[i] << " earn <in millions>: "; 
    cin >> earnings[i]; 
    cout << endl; 
} 
相關問題