Reputation: 194
I am a C++ beginner. Currently learning vectors. I am writing a program that calculates the average given the grades. The program I have written accepts only 5 grades. How can I modify the program so that the vector space is automatically allocated for any number of grades? That is, at the 'Enter grades:' prompt, I should be able to enter any number of grades and the average for those grades have to be calculated.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> grades;
int grade;
cout << "Enter grades: ";
for(int i = 1; i <= 5; ++i) {
cin >> grade;
grades.push_back(grade);
} double total = 0;
for(int i = 0; i < grades.size(); ++i) {
total += grades[i];
} double avg;
cout << "Average = " << total / grades.size() << endl;
return 0;
}
Upvotes: 1
Views: 1135
Reputation: 63946
It looks like you want the end-of-line (the user hitting "enter") to signify the end of the grades.
This code will pull that entire line into its own stream object which - unlike cin
- will eventually reach an end.
std::string grades_full_line;
std::getline(std::cin, grades_full_line);
std::stringstream grade_stream(grades_full_line);
You can now change your loop to use the stream itself as a conditional. It will evaluate to false
when you reach the end.
for( grade_stream >> grade; grade_stream; grade_stream >> grade )
{
grades.push_back(grade);
}
Upvotes: 3
Reputation: 581
Vectors are pretty cool in that they can grow as needed (if you're using the push_back method as you are). So essentially, you're already there! Your code will handle as many grades as you can put in (within reason).
What you will have to change is to change your for loop to loop the dynamically selected number of times:
Change:
for(int i = 1; i <= 5; ++i) {
cin >> grade;
grades.push_back(grade);
}
to
cout << "How many grades" << endl;
cin >> numOfGrades;
for(int i = 0; i < numOfGrades; ++i) {
cin >> grade;
grades.push_back(grade);
}
This will loop the right number of times and get you what you want.
Upvotes: 1
Reputation: 16777
You need to figure out a loop termination condition - some way for the user to let you know that he is done entering the grades. Once you incorporate that into the bounds on your push_back
loop, your code, as it stands, works. Lets say you decide that a grade of -1
implies that the user is done entering grades. Then the following modification is all you need:
while(cin >> grade and grade != -1)//EDITED
{
grades.push_back(grade);
}
EDIT : As cdhowie mentions, you should sanitize the input received.
Upvotes: 0