I am trying to print out the sum of the first 'x' elements within a vector. Basically, the user inputs a bunch of numbers (which are pushed back into the vector) and once they decide to exit the loop, they have to choose the number of elements that they want to sum.
For example, if they entered "6, 5, 43, 21, 2, 1
", they choose the numbers which they wish to sum, e.g. "3
". Finally, the output should be "The sum of the first 3 numbers is "6, 5, and 43 is 54
".
The only thing I have found was to find the sum of the vector which (I believe) is not much use to me.
I also checked a c++ website with the <vector>
library but can't figure if any of the functions are of much use. This is for c++ and bear in mind that, I am a new programmer.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// 1) read in numbers from user input, into vector -DONE
// 2) Include a prompt for user to choose to stop inputting numbers - DONE
// 3) ask user how many nums they want to sum from vector -
// 4) print the sum of the first (e.g. 3 if user chooses) elemens in vector.
vector <int> nums;
int userInput, n, total;
cout << "Please enter some numbers (press '|' to stop input) " << endl;
while (cin >> userInput)
{
if (userInput == '|')
{
break; //stops the loop if the input is |.
}
nums.push_back(userInput); //push back userInput into nums vector.
}
cout << "How many numbers do you want to sum from the vector (the numbers you inputted) ? " << endl;
cin >> total;
cout << nums.size() - nums[total]; //stuck here
return 0;
}