How to input numbers using auto loop in c++

Viewed 321

How to input numbers using auto loop in c++

For example I Have a products of burgers , fried and soda

#include <iostream>
#include <string>
#include <vector>


int main(){
    
    
    std::vector<std::string> products = {"burgers","fries","sodas"};
    std::vector<int> numbers = {};
    int a;
     for (auto n : products)
        std::cout <<"Enter number of "<< n << ": \n";
        std::cin >>a;
        numbers.push_back(a);

    return 0;
}

After i run this code this is the output

Enter number of burgers:
Enter number of fries:
Enter number of sodas:
1 // this is the only input

I want the output just like this

   Enter number of burgers:
    1 // input
    Enter number of fries:
    1 // input
    Enter number of sodas:
    1 // input
1 Answers

You need to put braces around the whole body of the loop. It's not like Python, the indentation does not mark the loop body:

     for (auto n : products) {
        std::cout <<"Enter number of "<< n << ": " << std::endl;
        std::cin >> a;
        numbers.push_back(a);
     }
Related