wubbalubba
wubbalubba

Reputation: 764

Intermittent issue getting input

Can someone explain to me what's wrong with this code? It works sometimes, i.e. if I input 5, 5, 5, -1 on the terminal, it'll return 15. But other times, it returns 0.

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int input; 
    vector<int> input_vector;
    cout << "Enter -1 when done" << endl;;
    
    cout << "Your int: ";
    cin >> input;
    while (input != -1) {
        input_vector.push_back(input);
        cout << "Your int: ";
        cin >> input;
    }

    int sum = 0;
    for (auto i : input_vector) {
        cout << "i: " << input_vector[i] << endl;
        sum += input_vector[i];
    }

    cout << "Sum: " << sum << endl;

    return 0;
}

Upvotes: 0

Views: 48

Answers (1)

Victor Eijkhout
Victor Eijkhout

Reputation: 5810

You use a range-based notation for (auto i : input_vector) which gives for i the actual values stored in the array. But then you use it as input_vector[i]. This is wrong: i is the value of the element, not the index. So replace input_vector[i] by i.

for (auto i : input_vector) {
    cout << "i: " << i << endl;
    sum += i;
}

Note that now you don't have the index any more, but for calculating a sum you don't need that.

Upvotes: 6

Related Questions