parse string to vector of int

This question already has an answer here:

  • The most elegant way to iterate the words of a string [closed] 74 answers

  • You can use std::stringstream . You will need to #include <sstream> apart from other includes.

    #include <sstream>
    #include <vector>
    #include <string>
    
    std::string myString = "10 15 20 23";
    std::stringstream iss( myString );
    
    int number;
    std::vector<int> myNumbers;
    while ( iss >> number )
      myNumbers.push_back( number );
    

    std::string myString = "10 15 20 23";
    std::istringstream is( myString );
    std::vector<int> myNumbers( std::istream_iterator<int>( is ), std::istream_iterator<int>() );
    

    或者,如果矢量已经被定义,则代替最后一行

    myNumbers.assign( std::istream_iterator<int>( is ), std::istream_iterator<int>() );
    

    这几乎是现在其他答案的重复。

    #include <iostream>
    #include <vector>
    #include <iterator>
    #include <sstream>
    
    int main(int argc, char* argv[]) {
        std::string s = "1 2 3 4 5";
        std::istringstream iss(s);
        std::vector<int> v{std::istream_iterator<int>(iss),
                           std::istream_iterator<int>()};
        std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    }
    
    链接地址: http://www.djcxy.com/p/19576.html

    上一篇: 在C ++中与java的string.split(“”)类似

    下一篇: 将字符串解析为int的向量