multiple numbers input on one line

后端 未结 3 1293
无人及你
无人及你 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:33

    main.cc

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main() {
        std::vector vec;
    
        std::string line;
        if(!std::getline(std::cin, line)) return 1;
        std::istringstream iss(line);
    
        std::copy(std::istream_iterator(iss),
            std::istream_iterator(),
            std::back_inserter(vec));
    
        std::copy(vec.begin(), vec.end(), std::ostream_iterator(std::cout, ", "));
    
        return 0;
    }
    

    stdin

    1 2 3 4 5
    

    stdout

    1, 2, 3, 4, 5,
    

    https://ideone.com/FHq4zi

提交回复
热议问题