【问题标题】:cin.getline doesn't let the user to enter the value [duplicate]cin.getline 不允许用户输入值[重复]
【发布时间】:2013-01-17 04:40:51
【问题描述】:

可能重复:
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

【问题讨论】:

标签: c++


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    相关资源
    最近更新 更多