How to parse comma delimited integers from a string in c++

后端 未结 4 561
轻奢々
轻奢々 2021-01-16 00:48

I have a function recieving a string, which is a pair of comma delimited integers in a fashion such as \"12,4\". How can I parse the integers out of this string?

相关标签:
4条回答
  • 2021-01-16 01:31

    Depends whether or not you can depend on the incoming data being valid. If you can, I'd do:

    #include <cstdlib>
    #include <utility>
    #include <string>
    
    std::pair<int, int> split(std::string const& str)
    {
        int const a = std::atoi(str.c_str());
        int const b = std::atoi(str.c_str() + str.find(',') + 1);
        return std::make_pair(a, b);
    }
    
    0 讨论(0)
  • 2021-01-16 01:32

    if you use Qt, you can use QString::split();

    0 讨论(0)
  • 2021-01-16 01:42

    std::getline implements the basic "split" functionality (I don't see it mentioned in the first few answers at the other question.)

    vector< int > numbers;
    
    istringstream all_numbers_iss( "12,4" );
    string number_str;
    int number;
    
    while ( getline( all_numbers_iss, number_str, ',' ) // separate at comma
            && istringstream( number_str ) >> number ) {
        numbers.push_back( number );
    }
    
    0 讨论(0)
  • 2021-01-16 01:49

    boost tokenizer works pretty well. Click here for example.

    0 讨论(0)
提交回复
热议问题