user3350597 user3350597 - 2 months ago 6
C++ Question

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.

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.

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();
}

Answer

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). Using skipws resolves the problem.

Comments