将(例如)12345:12-34 转换为三个整数:(12345, 12, 34) C++ 字符串?

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

将它们分成 3 个整数的最快方法是什么?我觉得这应该可以在一行中实现,但我能找到的最接近的是:

#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; 
} 

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

而 link 的作用在这里:https://godbolt.org/z/8sP9vvqfv 但首先它只会在 ':'s so far, not sure how to expand to ':'s and '- 之间分隔.但其次,这似乎过于复杂......这真的是最好的方法吗?

谢谢

how to expand to ':'s

您从输入中读取一个字符并检查它是否是 :。例如:

#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';
    }
}