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;


}

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!!

Whoever told you that was wrong. If you're going to take an arbitrary number of inputs, you need to let the loop go until you read an input telling you to stop (e.g. 0). Of course, this makes your marker an invalid input for the middle of the list (since it would break the loop), which is a consideration you have to make.

Duh!!!
What I was going to do WAS bad practice, which was a nested for loop to break the element insert loop.

I was just hung up on tracking the array position as a termination condition!

this is the solution for a dynamically expanding array.

for (vector <int>::size_type i = 0; input != 0; ++i)

i just monitored the variable for a 0 in the ORIGINAL loop.

Thanks.

This article has been dead for over six months. Start a new discussion instead.