1

我正在学习在 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:\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;
}
4

1 回答 1

2

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

cout << "Enter mark for student #1:"

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

一旦用户输入除 a 以外的其他内容double(例如EOF标志),循环就会退出。

于 2014-07-21T09:42:29.733 回答