C++ terminate called after throwing an instance of ‘std::out_of_range’ Simple Averaging code

Comp Sci 201 Student here. I’m running a simple averaging coded but I keep getting this error, any words of wisdom?

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {

int userIn = 0;
int numSum = 0;
cin >> userIn;

vector<int>v;

   for(int i = 0; userIn !=-1;i++) {
      v.at(i) = userIn;
      v.push_back(i);
      cin >> userIn;
   }

   for(unsigned i = 0; i <= v.size(); i+= 3) {
   numSum = v.at(i) + v.at(i+1) + v.at(i+2);
   }

   cout << numSum/3;

}

Keep getting this error terminate called after throwing an instance of

‘std::out_of_range’ what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)

after using an input of 4 4 4 –

Seems like it’s throwing out my vector, but shouldn’t my vector be a size of 3 now? Larger than 0?

Thanks, I know I’m a total newbie.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)