Hello all ,
I was experimenting with athis program using vectors.
The code below works, but is not my original intent.
Instead of arbitrarily adding 4 numbers, I wnted the program to keep
taking numbers and growing the vector dynamically as needed without
pre-allocating the resources.
i couldn't figure out how to keep testing for new integers, then doing a sum at whatever point an EOF is encouintered ( or perhaps a zero?).
The only way seemed to invole breaking the element insert loop.
I have been told that this is BAD PRACTICE!!
How can this be done correctly?
Also, i had to initialize the sum variable to 0 . Otherwise I got a large
number output that had nothing to do with the sum. (something like an overflow). Why did this happen?
#include <iostream>
#include <vector>
using namespace std;
vector <int> intv;
main()
{
int input,sum(0);
for (vector <int>::size_type i = 0; i != 4; ++i)
{
cout << "Enter a number";
cin >>input;
intv.push_back(i);
intv[i] = input;
}
//read them out
for (vector <int>::iterator iter= intv.begin() ;iter !=intv.end();++iter)
{
cout << "the values are: " << *iter << endl;
sum += *iter;
}
cout << "The sum of these numbers is " << sum << endl;
}