multiple numbers input on one line

后端 未结 3 1297
无人及你
无人及你 2021-02-10 23:00

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

3条回答
  •  醉酒成梦
    2021-02-10 23:42

    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 
    #include 
    #include 
    #include 
    #include 
    
    int main() 
    {
        std::string s;
    
        std::getline( std::cin, s );
    
        std::istringstream is( s );
    
        std::vector v( ( std::istream_iterator( is ) ), std::istream_iterator() );
    
        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 v( ( std::istream_iterator( is ) ), std::istream_iterator() );
    

    for

    std::vector v;
    int x;
    
    while ( is >> x ) v.push_back( x );
    

提交回复
热议问题