c++:使用特定的命令退出for循环push_back命令

C++: exiting a for loop push_back command with a specific command

本文关键字:命令 for 退出 循环 push back c++      更新时间:2023-10-16

我正在学习c++中的push_back向量,我到了可以使用它的地方。然而,我所编写的代码(粘贴在下面)在每次循环结束时询问用户是否想要继续循环。我发现这非常不方便,所以我想更改代码,当用户输入("EXIT")时,它将中断for循环。在这种情况下,我该如何更改代码呢?我粘贴了整个代码,以防我可能需要更改for循环之外的部分。

#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:tt"<<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;
}

只要用户输入有效的标记,就可以留在循环中:

cout << "Enter mark for student #1:"
while(cin >> mark) {
    students_marks.push_bak(mark);
    cout << "Enter mark for student #" << marks.size() + 1;
}

当用户输入double以外的标志,例如EOF标志时,循环将退出。