Dynamically add variables in C++

user1386320 picture user1386320 · Nov 5, 2012 · Viewed 7.2k times · Source

I'm working on a project for school. This is the case:

You should be able to input weights for n number of students. Calculate average weight of students and output how many students are weighting less than 65 kg's.

By now I have this sample of C++ source:

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int number_of_students;

    cout << "How many students would you like to add?: ";
    cin >> number_of_students;
    cout << endl;
    cout << endl;

    cout << "--------------------------------------------" << endl;
    cout << "---------- ENTER STUDENT'S WEIGHT ----------" << endl;
    cout << "--------------------------------------------" << endl;
    cout << endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

Which is basically nothing because I'm stucked currently. I do not know who can I add for example 6 new variables of weight when the user inputs for example 6 students.

EDIT:

I can do the average weight calculation and find how many students weigh less than 65 kg's. Only I'm stucked at defining number of variables of how many students will be added. Calculate average weight of students and output how many students are weighting less than 65 kg's.

Answer

leftaroundabout picture leftaroundabout · Nov 5, 2012

You need to store the weights in some kind of container with variable size. It's very much recommended to use containers from the standard library, the most typical choice is std::vector.

#include<vector>
#include<algorithm>  //contains std::accumulate, for calculating the averaging-sum

int main(int argc, char *argv[])
{
    int number_of_students;

    cout << "How many students would you like to add?: ";
    cin >> number_of_students;
    cout << endl;
    cout << endl;

    cout << "--------------------------------------------" << endl;
    cout << "---------- ENTER STUDENT'S WEIGHT ----------" << endl;
    cout << "--------------------------------------------" << endl;
    cout << endl;

    std::vector<float> weights(number_of_students);

    for(int i=0; i<number_of_students; ++i) {
      cin >> weights[i];
    }

    cout << "Average is: " << std::accumulate(weights.begin(), weights.end(), 0.f)
                                      / number_of_students
      << std::endl;

    return EXIT_SUCCESS;
}