-2

I am trying to use c++ to sum 3 integers from the input, but I keep get 0. Please help thx.

  vector<int> x;
  x.reserve(3);
  cin >> x[0] >> x[1] >> x[2];
  int sum = std::accumulate(x.begin(), x.end(), 0);
  cout << sum << endl;
  return 0;

1

2

3

0

Xiong chenyu
  • 135
  • 1
  • 9
  • 2
    `cin >> x[0] >> x[1] >> x[2]` has undefined behaviour, since `x.size()` is zero. Once behaviour is undefined, all bets are off for any behaviour of your program. Do `x.resize(3)` rather than `x.reserve(3)`. All `x.reserve(3)` does is avoid need for reallocation on resizing for new sizes between `1` and `3`. It doesn't resize on its own. – Peter Mar 10 '19 at 12:40
  • I have the fixed code here: https://ideone.com/7587E6 – drescherjm Mar 10 '19 at 12:42
  • 2
    Good submittal, but in general, it should compile. Consider that, because "how many int" is seldom fixed, you are more likely to want to count how many input "on the fly". So perhaps use a loop, cin to a local var, then x.push_back( a_local_var), and repeat until some condition (maybe eof(), or local var == -1, etc.) x.size() is your counter. – 2785528 Mar 10 '19 at 12:52
  • Thanks for the help. Now I understand the difference between capacity and size. – Xiong chenyu Mar 11 '19 at 02:24

3 Answers3

1

vector::reserve(size_type n) will request a change in the capacity of the vector, not the size. You can use the resize function, or even better the constructor.

int main()
{
    std::vector<int> x(3,0);  //set the size to 3 and fill with zeros.

    std::cin >> x[0] >> x[1] >> x[2];

    int sum = std::accumulate(x.begin(), x.end(), 0);
    std::cout << sum << std::endl;
}

You can read this answer here for the differences between reserve vs resize.

Constantinos Glynos
  • 2,952
  • 2
  • 14
  • 32
0

Fill your vector first with something if not you will probably get undefined

vector<int> x(3,0);
J.lan
  • 223
  • 4
  • 17
0

use c++ to sum 3 integers from the input why accumulate always return 0

This answer uses push_back(), and does not need to know how many integers are input, as the vector will auto expand; In this way it sidesteps the issues of std::vector that were defeating your code.

Consider that, because a "how many int" might be submited is seldom fixed you are more likely to want to count how many input "on the fly". So perhaps use a loop, cin to a local var, then x.push_back( a_local_var), and repeat until some condition (maybe eof(), or local var == -1, etc.) x.size() is your counter.

Here is a functioning example, using command line vars and eof() (and a vector and accumulate).

 // Note: compile with -std=c++17 for the using comma list
 #include <iostream>
 using std::cout, std::cerr, std::endl, std::hex, std::dec, std::cin, std::flush; // c++17

 #include <vector>
 using std::vector;

 #include <string>
 using std::string;

 #include <sstream>
 using std::stringstream;

 #include <numeric>
 using std::accumulate;

 #include <cassert>


 class T951_t // ctor and dtor compiler provided defaults
 {
 public:
    int operator()(int argc, char* argv[]) { return exec(argc, argv); } // functor entry

 private:

    stringstream ssIn; // to simulate user input

    int exec(int argc, char* argv[])
       {
          int retVal = initTest(argc, argv); // transfer command line strings into ssIn
          if(retVal != 0) return retVal;

          // ------------------------------------------------------------
          // simulate unknown quantity of ints

          vector<int> x;

          do {
             int localInt = 0;
             ssIn >> localInt;

             if(!ssIn.good())  // was transfer ok?
             {                 // no
                if (ssIn.eof()) break; // but we tolerate eof
                // else err and exit
                cerr << "\n  !ssIn.good() failure after int value " 
                     << x.back() << endl;
                assert(0);  // harsh - user typo stops test
             }
             x.push_back(localInt); // yes transfer is ok, put int into vector

             //cout << "\n  " << localInt;  // diagnostic
          } while(true);

          showResults(x);

          return 0;
       }

    // this test uses a stringstream (ssIn) to deliver input to the app
    // ssIn is initialized from the command line arguments
    int initTest(int argc, char* argv[])
       {
          if (argc < 2) {
             cerr << "\n  integer input required" << endl;
             return -1;
          }
          // test init
          for (int i=1; i < argc; ++i) {
             // cout << "\n  " << argv[i]; // diagnostic
             ssIn   << argv[i] << " ";     // user text into stream
          }
          cout << endl;
          return 0;
       }

    // display size and contents of vector x
    void showResults(vector<int> x)
       {
          cout << "\n  x.size(): " << x.size() << endl;

          int sum = std::accumulate(x.begin(), x.end(), 0);

          for (auto i : x)
             cout << "  " << i;
          cout << endl;

          cout << "\n  sums to: " << sum << '\n' << endl;
       }


 }; // class T951_t


  int main(int argc, char* argv[]) { return T951_t()(argc, argv); } // call functor

Tests:

./dumy951 1 2 3 55 12345678900 <-- fail after 55 because last int too big

./dumy951 1 2 3 y 55 12345678900 <-- fail after int value 3 (invalid int)

./dumy951 1 2 3 4 5 6 7 8 9 10 <-- success, result is 55

2785528
  • 5,438
  • 2
  • 18
  • 20