sscanf equivalent for std::string

sscanf equivalent for std::string

本文关键字:string std for equivalent sscanf      更新时间:2023-10-16

我有一个格式为std::string str =" 1001 0104 2325 9999"的字符串,我需要以整数形式存储这四个由空格分隔的子字符串。是否有一种优雅的方式来完成这个任务,就像C中的字符串一样(使用sscanf) ?这不是作业问题。

最干净的方法可能是将stringstream与istream_iterator一起使用,如下所示:

std::string str = "1001 0104 2325 9999";
std::istringstream in(str);
std::vector<int> numbers {
    std::istream_iterator<int>(in),
    std::istream_iterator<int>()
};
// just to show what we did:
for (int i : numbers)
    std::cout << i << "n";

请注意,在您提供的输入中有一点模糊:不清楚您是打算将0104设置为十进制还是八进制(因为前导零会导致在源代码中解释它)。我上面写的代码将其解释为十进制。如果您希望前导0表示八进制(并且前导0x表示十六进制),您可以通过将转换的基数设置为0来做到这一点(至少在内存可用的情况下)。