简体   繁体   中英

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.

The answer is quite simple. Read an int n indicating the number of items, then declare a std::vector<int> (or use std::array ) and read in n elements in a loop, pushing each onto the vector.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM