0

可能重复:
cin.getline() 正在跳过 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
4

1 回答 1

0

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

string temp;
cin.getline(temp, 30);
stringstream sst(temp);
sst >> m1.lenght;
于 2013-02-01T19:50:42.180 回答