1

Unable to take input from user and store it in a vector. How to do that? Just started learning to code.

#include<iostream>
#include<vector>

int main() {
int total_even = 0;
int product_odd = 1;
std::vector<int>numbers;
std::cout << "Enter 6 digits: ";
std::cin >> numbers;

for (int i = 0; i < numbers.size(); i++) {

    if (numbers[i] % 2 == 0) {

        total_even = total_even + numbers[i];
    }
    else {
        product_odd = product_odd * numbers[i];
    }
}
std::cout << "Sum of numbers is: " << total_even << "\n";
std::cout << "Product of odd numbers is: " << product_odd << "\n";
return 0;
}
Mehdi Mostafavi
  • 880
  • 1
  • 12
  • 25
john
  • 13
  • 2

1 Answers1

1

This is how you take inputs in a vector:

std::vector<int> numbers;
for(int i = 0; i < /*6 in your case*/; i++) {
    int temp;
    if(scanf("%d",&temp)) {
        numbers.push_back(temp);
    }
    else {
        std::cerr << "something wrong with vector" << "\n";
    }
}

Another way would be using a for-each loop. But, you need to know the size before hand in this case:

std::vector<int> numbers(size);
for(auto& elem : numbers) {
    std::cin >> elem;
}

For more information, take a look at How does c++ std::vector work?

kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39
  • 1
    you can also check using *cin*, `if (std::cin >> temp) numbers.push_back(temp); else { ... }`, note to be able to read again int it is needed to clear the flag and to bypass the non valid int, like `std::cin.clear(); std::cin.ignore(std::numeric_limits::max(), '\n');` – bruno Jul 04 '20 at 09:17
  • I put an answer for a similar case in https://stackoverflow.com/a/56585205/2458991 – bruno Jul 04 '20 at 09:28