Search code examples
c++stringtype-conversionintegerdata-conversion

Convert (for example) 12345:12-34 into three ints: (12345, 12, 34) C++ string?


What is the fastest way to seperate these into 3 ints? I feel like this should be possible in one line but the closest I can find is this:

#include <ostream> 
#include <iostream> 
#include <string> 
#include <sstream> 
#include <vector> 
 
std::vector<int> extract_ints(std::string const& input_str) 
{ 
    std::vector<int> ints; 
    std::istringstream input(input_str); 
 
    std::string number; 
    while (std::getline(input, number, ':')) 
    { 
        std::istringstream iss(number); 
        int i; 
        iss >> i; 
        ints.push_back(i); 
    } 
 
    return ints; 
} 
int main() 
{ 
    typedef std::vector<int> ints_t; 
 
    ints_t const& ints = extract_ints("3254:23-45"); 
    for (ints_t::const_iterator i = ints.begin(), i_end = ints.end(); i != i_end; ++i) 
        std::cout << *i << std::endl; 
 
    return 0; 
} 

Found here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/411271cd-5e8a-46f9-a78b-a49a347741c0/comma-delimited-string-to-integer-array?forum=vcgeneral

And the link to that in action is here: https://godbolt.org/z/8sP9vvqfv but first of all it will only seperate between ':'s so far, not sure how to expand to ':'s and '-'s also. But secondly, this just seems overly complicated... Is this really the best method to do this?

Thanks


Solution

  • how to expand to ':'s

    You read a char from input and check if it's a :. For example:

    #include <iostream>
    #include <exception>
    #include <vector>
    #include <sstream>
    #include <exception>
    std::vector<int> extract_ints(std::string const& input_str) 
    { 
        std::vector<int> r(3); 
        std::istringstream iss(input_str); 
        char c1;
        char c2;
        if (!(
             iss >> r.at(0) >> c1 >> r.at(1) >> c2 >> r.at(2) &&
             c1 == ':' && c2 == '-' &&
             !(iss >> c1)  // test if we are at EOF
        )) {
            throw std::runtime_error("Och och, invalid string");
        }
        return r;
    }
    int main() {
        for (auto&& i : extract_ints("3254:23-45")) {
            std::cout << i << '\n';
        }
    }