2

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;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 2
    Does `if (userInput == '|')` actually work? Are you sure you're reading in all the values? And what happens if the user wants to input the integer version of `|`? – cigien Aug 08 '20 at 17:25
  • Try giving `124` and it will stop reading input if your system uses Shift_JIS or UTF-8 (or other ASCII-compatible character code). – MikeCAT Aug 08 '20 at 17:27
  • 3
    *I also checked a c++ website with the " library but cant figure if any of the functions are of much use* -- You checked the wrong category. The category of functions you should be checking are the STL algorithm and numeric functions that work with containers of values. In this case, you would be looking for `std::accumulate` (answers below already given). – PaulMcKenzie Aug 08 '20 at 17:30
  • @cigien well I tested the program using it, and the loop takes in user input until | is pressed, so it does work (although i have probably written the code out in a bad way) – matiboy212121 Aug 08 '20 at 17:43
  • @MikeCAT thanks, i am aware of that. However, the exercise I am working on told me to use the 'int' data type so i guess il stick to that for the time being. – matiboy212121 Aug 08 '20 at 17:44
  • @PaulMcKenzie Appreciate it! I will look into that – matiboy212121 Aug 08 '20 at 17:45

2 Answers2

3

You can use std::accumulate from the <numeric>, to calculate the sum of a range, as follows.

#include <numeric>  // std::accumulate
#include <vector>

int sumUpTo(const std::vector<int>& vec, const std::size_t total)
{
    if (total > vec.size()) 
    // if the index exceeds the vec size
    // return the sum of the conatining elelemnts or provide an exception
        return std::accumulate(vec.begin(), vec.end(), 0); 
    
    return std::accumulate(vec.begin(), vec.begin() + total, 0);
}

(See a demo)


Also comparing the integer with a char here

if (userInput == '|') 

will fail when the user enters 124, because (int)'|' == 124. You need to rethink this part. My suggestion would be asking the user the number of elements he/she wants to input beforehand and run the loop only for that.

Also do not practice with using namespace std;

JeJo
  • 30,635
  • 6
  • 49
  • 88
  • Thanks for the detailed answer, JeJo. Is the main chunk of code a function which I should call within main? I have also seen that a lot of people neglected the use of "using namespace std;", but recommeded it for beginners.. I guess il just use std:: from now on, cheers! – matiboy212121 Aug 08 '20 at 17:47
  • @matiboy212121 Yes need to define the function outside the main and call it like: `cout << sumUpTo(nums, total);`, or if you are sure that the user entry `total` is never > size of the vector, call directly `cout << std::accumulate(vec.begin(), vec.begin() + total, 0);` – JeJo Aug 08 '20 at 17:50
  • 1
    Returning `-1` is odd. How do you distinguish between a sum of `-1`? Maybe return the sum of everything if there are insufficient elements? – cigien Aug 08 '20 at 17:50
  • @cigien Ok thanks I did just that, but for some reason "total" is undefined even though i have it listed alongside the other variables... – matiboy212121 Aug 08 '20 at 17:59
2

You can use std::accumulate from header <numeric>, as follows

std::cout << std::accumulate(nums.begin(), nums.begin()+total,0);
asmmo
  • 6,922
  • 1
  • 11
  • 25