Sorry for the topic title; I couldn't really think of anything better.
My question is this: I need to use a loop to input integers from the user and store them for later use. The loop is supposed to continue gathering integers until the user inputs '999'. I understand the loop part, just not storing variables on the fly. I can't declare them earlier in the code since I don't know how many there will be.
Can anybody nudge me in the right direction here? Any help would be appreciated.
Arrays work if you're program knows how many values there will be (like, a maximum of 100 inputs)
otherwise vectors are a good solution, because they can hold a variable amount of data.
//With Arrays
#include <iostream>
usingnamespace std;
int main()
{
int input[100];
int numOfInputs = 0;
int x;
while(true) //loop forever
{
cin >> x; //get a value
if(numOfInputs == 100) //if the user has already entered the max amount of data
break; //exit the loop
if(x == 999) //if the user entered 999
break; //exit the loop
else
{
input[numOfInputs] = x; //otherwise store the value of x in input
++numOfInputs; //and increment numOfInputs
}
}
}
Vectors are pretty handy containers. My examples put you on the right track, you can add on/take off of them to meet your needs.
I now have my vector functioning properly. What I need to know now is how to implement the vector (meaning finding the sum, product, etc. of the integers contained and finding the max and min of the numbers stored).
Once again, any help that you could give me would be great.
EDIT: I just wanted to state that I am not using these forums as an easy way out. My textbook does a horrible job of explaining certain things, vectors being one of them. That is the reason that I come to these forums, not to be a leech.
Well if you take a looksy at this link again: http://www.cplusplus.com/reference/stl/vector/ and scroll down a bit, you will find the functions of a vector. Click on them and you will be shown a description and a snippet of example code. That would probably help a lot for present and future vector use/reference.
You will find all of the information in that link, I'll explain in words though.
1. Create a variable for the sum (or product, etc)
2. Loop through the vector from 0, to the size of the vector - functions necessary in the link
3. During the loop, add each part of the vector to the sum variable
4. use sort() -which is in <algorithm>- (or google sorting methods, that's always good knowledge to have) to sort the vector from least to greatest
5. pulling out the max/min is easy from there.