2013-02-01 69 views
0

可能重複:
cin.getline() is skipping an input in C++cin.getline不會讓用戶輸入值

我工作的C++,拿到2部電影像一些數據以下:

struct Movie m1, m2; 
    cout << "Enter first movie title: "; 
    cin.getline(m1.title, 30); 
    cout << "Enter first movie director: "; 
    cin.getline(m1.director, 30); 
    cout << "Enter first movie length: "; 
    cin >> m1.length; 

    cout << "Enter second movie title: "; 
    cin.getline(m2.title, 30); 
    cout << "Enter second movie director: "; 
    cin.getline(m2.director, 30); 
    cout << "Enter second movie length: "; 
    cin >> m2.length; 

但是,我很驚訝,在輸出它並不是所有我輸入第二部電影的標題。下面是輸出

Enter first movie title: Girl 

Enter first movie director: GirlD 

Enter first movie length: 10 

Enter second movie title: Enter second movie director: Boy 

Enter second movie length: 20 
+0

HTTP ://stackoverflow.com/search q =函數getline +跳過。或者,瀏覽右側標有「相關」的欄。 – chris

回答

0

cin >> m1.length;,其唯一的閱讀次數,所以給人們留下了\n,接下來的函數getline將讀取的空行,所以你可以把它讀作這樣的:

string temp; 
cin.getline(temp, 30); 
stringstream sst(temp); 
sst >> m1.lenght;