cin.getline 不允许用户输入值

cin.getline doesn't let the user to enter the value

本文关键字:输入 用户 不允许 getline cin      更新时间:2023-10-16

可能的重复项:
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
cin >> m1.length;

它只读取数字,所以它离开n,下一个getline会读取空行,所以你可以这样读:

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