'How to get multiple input from user in one line c++

5
1 2 3 4 5

the first line is how many input will user give. and the second line is the input from the user. basically it's "c >> a >> b >> c;" but it's up to the user how many input they want.

c++


Solution 1:[1]

The answer is quite simple. Read an int n indicating the number of items, then declare a std::vector<int> and read in n elements in a loop, pushing each onto the vector. This can be done either with an explicit for loop, or using STL functions.

Solution 2:[2]

It's simple to read input and store in std::vector. You can resize the vector to hold n elements by passing n to its constructor. Then you can read into the std::vector like you do for a normal array.

#include <vector>
#include <iostream>

int main()
{
    int n;
    std::cin >> n;
   
    std::vector<int> v(n);
    for (int i = 0; i < n; i++)
        std::cin >> v[i];
    
    for (int i = 0; i < n; i++)
        std::cout << v[i] << std::endl;
}

Solution 3:[3]

I would be inclined to use a std::vector over any other data type.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main()
{
  std::vector <int> xs;

  int n;
  std::cin >> n;

  // method 1
  std::copy_n( std::istream_iterator <int> ( std::cin ), n, std::back_inserter( xs ) );

  // method 2
  int x; while (n--) { std::cin >> x; xs.push_back( x ); }

In general, your goal should not be to do things “in one line”, but to do things correctly and succinctly, favoring correctness over terseness.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 kiner_shah
Solution 3 Dúthomhas