简体   繁体   English

向量无法正常运作的功能

[英]Function with vectors not working properly

When I call the function for the first time it works fine. 当我第一次调用该函数时,它可以正常工作。

But when I call the function for the second time it just jumps over first part of the code, where I am trying to add a new name to the vector vec_name and sends me to the for loop. 但是,当我第二次调用该函数时,它只是跳过了代码的第一部分,在这里我试图为向量vec_name添加一个新名称,并将我发送到for循环。

void addNewStudent(int num) 
{
    string name;
    cout << "Add new student" << endl;
    cout << "Name : ";
    getline(cin, name);

    vec_name.push_back(name);   

    float avg = 0;
    for (int i = 1; i <= num; i++)
    {
        float temp;
        cout << endl << "Enter " << i << " grade : ";
        cin >> temp;
        avg += temp;
    }
    avg /= num;

    vec_avg.push_back(avg);
}

What am I doing wrong? 我究竟做错了什么?

I added cin.ignore() at the end of the function. 我在函数末尾添加了cin.ignore()。

void addNewStudent(int num) 
{
    string name;
    cout << "Add new student" << endl;
    cout << "Name : ";

    getline(cin, name);

    vec_name.push_back(name);   

    float avg = 0;
    for (int i = 1; i <= num; i++)
    {
        float temp;
        cout << endl << "Enter " << i << " grade : ";
        cin >> temp;
        avg += temp;
    }
    avg /= num;

    vec_avg.push_back(avg);

    cin.ignore();
}

Change 更改

cin >> temp;

into 进入

cin >> temp >> skipws;

Calling getline (in the second function call) after cin (of the first function call) will read an empty string (the newline of the previous cin ). cin (第一个函数调用中)之后调用getline (在第二个函数调用中)将读取一个空字符串(上一个cin的换行符)。 Using skipws resolves the problem. 使用skipws解决了该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM