首页 > 解决方案 > 有什么方法可以将来自用户输入的多个 int 存储到向量中?

问题描述

我试图通过让用户输入他们收到的成绩来将多个 int 存储到一个向量中。但是我确实相信有一个更简化的版本来尝试这样做。有单独的功能会更好吗?有没有人可以指导我正确的方向?

#include <iostream>
#include <vector>
#include <numeric>
using namespace std; 

int main() {
  cout << "Welcome to the Grade Calculator! \n"
       << "What is the student's full name? ";
  string student_name;
  getline(cin,student_name);
  cout << "\nPlease input the points earned for each assignment.";
  
  vector<int> student_grades(8); 
    cout << "\nLab 2: ";
    cin >> student_grades[0];
    cout << "Lab 3: ";
    cin >> student_grades[1];
    cout << "Lab 4: ";
    cin >> student_grades[2];
    cout << "Lab 5: ";
    cin >> student_grades[3];
    cout << "Lab 6: ";
    cin >> student_grades[4];
    cout << "Lab 7: ";
    cin >> student_grades[5];
    cout << "Lab 8: ";
    cin >> student_grades[6];
    cout << "Lab 9: ";
    cin >> student_grades[7];
    cout << "Lab 10: ";
    cin >> student_grades[8];
    
  //Finding sum of the grades
  int sum_of_grades = accumulate(student_grades.begin(),student_grades.end(),0);
  //Console Output
  cout << '\n'<< student_name << " has earned " << sum_of_grades << " points in the course, so far." << endl;
  cout << "\nThere are 2000 points possible in this course." << endl;
  cout << "\nInput the anticpated score for the final project (200 points possible): ";
  int anticipated_score;
  cin >> anticipated_score;
  int total_score = sum_of_grades+anticipated_score;
  cout << "Total Projected Assignment Points: " << total_score << endl;
  
  cout << "\nFinal Exam Score Needed for Final Course Grade (1000 Points Possible)"
       << "\nTo Earn an A, need at least: " << 1800 - total_score << " points, for a total of: 1800"
       << "\nTo Earn a B, need at least: " << 1600 - total_score << " points, for a total of: 1600"
       << "\nTo Earn a C, need at least: " << 1400 - total_score << " points, for a total of: 1400"
       << "\n To Earn a D, need at least: " << 1200 - total_score << " points, for a total of: 1200" << endl;
       
  return 0;

}

标签: c++c++11

解决方案


您可以使用 for 循环:

for(int i = 0; i < 8; ++i){
    cout << "\nLab " << i+2 << ": ";
    cin >> student_grades[i];
}

该代码本质上等同于您在程序中编写的代码;它遍历所有可能的索引,提示用户在vector.


推荐阅读