Home > Blockchain >  Intermittent Issue Getting Input on C
Intermittent Issue Getting Input on C

Time:04-24

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;
}

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related