How to read space separated numbers from console?

后端 未结 5 1751
无人共我
无人共我 2021-01-12 03:13

I\'m trying to do a simple task of reading space separated numbers from console into a vector, but I\'m not getting how to do this properly.

5条回答
  •  一生所求
    2021-01-12 03:20

    To elaborate on jonsca's answer, here is one possibility, assuming that the user faithfully enters valid integers:

    string input;
    getline(cin, input);
    
    istringstream parser(input);
    vector numbers;
    
    numbers.insert(numbers.begin(),
                   istream_iterator(parser), istream_iterator());
    

    This will correctly read and parse a valid line of integers from cin. Note that this is using the free function getline, which works with std::strings, and not istream::getline, which works with C-style strings.

提交回复
热议问题