multiple numbers input on one line

2020-06-06 01:20发布

I want to know how I can accept multiple numbers on one line without exactly knowing in advance how many.

So for example if I have 1 2 3 4 as input I could use :

cin >> a >> b >> c >> d;

But if I don't know that the amount is 4 then I can't use that approach. What would be the right way to store the input into a vector?

Thanks in advance

标签: c++ input
3条回答
一纸荒年 Trace。
2楼-- · 2020-06-06 01:54

You can read all input until the new line character in an object of type std::string and then extract numbers from this string and place them for example in a vector.

Here is a ready to use example

#include <iostream>
#include <sstream>
#include <iterator>
#include <string>
#include <vector>

int main() 
{
    std::string s;

    std::getline( std::cin, s );

    std::istringstream is( s );

    std::vector<int> v( ( std::istream_iterator<int>( is ) ), std::istream_iterator<int>() );

    for ( int x : v) std::cout << x << ' ';
    std::cout << std::endl;

    return 0;
}

If you would input a line of numbers

1 2 3 4 5 6 7 8 9 

then the program output from the vector will be

1 2 3 4 5 6 7 8 9 

In this program you could substitute statement

std::vector<int> v( ( std::istream_iterator<int>( is ) ), std::istream_iterator<int>() );

for

std::vector<int> v;
int x;

while ( is >> x ) v.push_back( x );
查看更多
乱世女痞
3楼-- · 2020-06-06 02:10

main.cc

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

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

    std::string line;
    if(!std::getline(std::cin, line)) return 1;
    std::istringstream iss(line);

    std::copy(std::istream_iterator<int>(iss),
        std::istream_iterator<int>(),
        std::back_inserter(vec));

    std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, ", "));

    return 0;
}

stdin

1 2 3 4 5

stdout

1, 2, 3, 4, 5,

https://ideone.com/FHq4zi

查看更多
地球回转人心会变
4楼-- · 2020-06-06 02:15

Put it inside a loop:

int x;
while ( cin>>x )
  vec.push_back(x);
查看更多
登录 后发表回答