从 std::string C++中提取任意数据值

Extract arbitrary data values from a std::string C++

本文关键字:任意 数据 提取 C++ std string      更新时间:2023-10-16

我有这样的字符串

10z45
9999i4a

基本上int-char-int-optionalchar

我想做这个函数原型

void process(std::string input, int &first, char &c, int &last, bool &optional)

唯一的问题是我不确定迭代字符串以提取这些值的最佳方法。 宁愿不使用正则表达式库,似乎可以简单地完成?

使用字符串流:

#include <sstream>
...
std::istringstream iss(input);
iss >> first >> c >> last >> optional;

如果没有最终字符,则不会触及optional的值,因此我建议事先将其设置为 0。

使用 std::istringstream ,读取 int、char

、int,然后尝试下一个 char:

std::istringstream is(input);
is >> first >> c >> last;
char c2;
optional = (is >> c2);

我不确定这是你想要的 100% - 但我会这样做。