【问题标题】:getline does not take any input [duplicate]getline 不接受任何输入
【发布时间】:2016-01-24 16:52:34
【问题描述】:

当用户输入姓名和姓氏时,我需要使用 getline 来存储整行。当我运行程序时,它通过 getline(cin,st[i].name); 行我的意思是输入功能不起作用,它会跳过下一个用于“分数”的 cin。

struct Student {
    string name;
    int score;
    char grade;
};

void main() {
    int SIZE;
    cout << " How many students are you going to add ? ";
    cin >> SIZE;
    Student* st = new Student[SIZE]; // user determines size of array.
    int i;
    for (i = 0; i < SIZE; i++)
    {   
        if (st[i].name.empty()) // if array list of name is empty, take input.
        {
            cout << "name and surname : ";
            //cin >> st[i].name;
            getline(cin, st[i].name);
        }
        cout << "Score : ";
        cin >> st[i].score; // take quiz score from user.

-- 我没有放整个 main 函数。

所以当我运行程序时,会显示返回屏幕

还有其他方法可以获取 name 的输入吗?

【问题讨论】:

    标签: c++ arrays struct getline


    【解决方案1】:

    cin &gt;&gt; SIZE; 之后,结尾的换行符仍保留在标准输入中。

    您需要cin.ignore() 来跳过剩余的换行符,以便后面的getline() 可以获取该值。

    【讨论】:

    • 谢谢先生。它有效,但我还有一个问题。我还应该使用 cin.clear() 吗?还是我需要写 cin.ignore(1000, '\n') 而不是 () ?
    • 好吧,你可以在#include &lt;limits&gt; 之后写cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n');。这将成功忽略流中剩余的字符。
    猜你喜欢
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多