cin.getline不允许用户输入值

时间:2013-02-01 19:25:38

标签: c++

  

可能重复:
  cin.getline() is skipping an input in C++

我正在研究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

1 个答案:

答案 0 :(得分:0)

cin >> m1.length;,它只读取数字,所以离开\n,下一个getline会读取空行,所以你可以这样读:

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