Home > Net >  How to get multiple input from user in one line c
How to get multiple input from user in one line c

Time:01-27

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.

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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.

  •  Tags:  
  • Related