input n space separated integers in c++

Here is the code to input n space-separated integers in C++ along with explanations for each step:

#include <iostream>
#include <vector>

int main() {
    int n;
    std::cin >> n; // Step 1: Read the value of n from the user

    std::vector<int> numbers(n); // Step 2: Create a vector to store the numbers

    for (int i = 0; i < n; i++) {
        std::cin >> numbers[i]; // Step 3: Read each number from the user and store it in the vector
    }

    // Step 4: Print the numbers
    for (int i = 0; i < n; i++) {
        std::cout << numbers[i] << " ";
    }

    return 0;
}

Explanation:

  1. Step 1: Read the value of n from the user using the std::cin >> n statement. This statement reads an integer value entered by the user and assigns it to the variable n.

  2. Step 2: Create a vector named numbers with a size of n using the statement std::vector<int> numbers(n). The vector is used to store the input numbers.

  3. Step 3: Use a for loop to iterate n times. Inside the loop, read each number from the user using the statement std::cin >> numbers[i]. The numbers are stored in the vector numbers at the corresponding index i.

  4. Step 4: After reading all the numbers, use another for loop to print the numbers. The loop iterates n times, and each number is printed using the statement std::cout << numbers[i] << " ";. The numbers are separated by a space.

That's it! The code reads n space-separated integers from the user and stores them in a vector. Then, it prints the numbers.