I was learning to push_back vectors in C++, and I got to where I can use it. However, the code I made, pasted below, asks the user every time the loop ends if the user wants to continue the loop or not. I found this very inconvenient, so I wanted to change the code to where when the user inputs ("EXIT"), it would break the for loop. How would I have to change the code in this case? I pasted the whole code just in case I may have to change the portions besides the for loop.
#define all student_marks.begin(), student_marks.end()
using namespace std;
int main()
{
vector<double> student_marks; //create container
double mark;
char more_students = 'y'; //set default to yes ('y')
while (more_students=='y' || more_students=='Y') {
cout<<"Enter mark for student #"<<student_marks.size()+1<<":";
cin>>mark; //enter mark
student_marks.push_back(mark); //push_back
cout<<"More students?(y/n)";
cin>>more_students; //user selects to break or continue the loop
}
double sum = accumulate(all, 0.0), average = sum/student_marks.size(); //sum and ave
cout<<endl
<<"Total mark:\t\t"<<sum<<endl
<<"Average mark:\t"<<average<<endl
<<"Highest mark:\t"<<*max_element(all)<<endl
<<"Lowest mark:\t"<<*min_element(all)<<endl<<endl;
cout<<"-----Score list-----"<<endl;
sort(all,greater<double>()); //sort list
for (size_t i=0; i<student_marks.size(); i++)
cout<<"#"<<i+1<<". "<<student_marks[i]<<endl; //outputs results as list
return 0;
}
You could just stay in the loop as long as the user inputs valid marks:
cout << "Enter mark for student #1:"
while(cin >> mark) {
students_marks.push_bak(mark);
cout << "Enter mark for student #" << marks.size() + 1;
}
The loop will exit as soon as the user enters something other than a double
, e.g. the EOF
flag.