简体   繁体   English

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

[英]Extract arbitrary data values from a std::string C++

I have strings like this 我有这样的字符串

10z45
9999i4a

Basically int-char-int-optionalchar 基本上是int-char-int-optionalchar

I want to do this function prototype 我想做这个函数原型

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

Only thing is I'm not sure the best way to iterate over the string to extract these values. 唯一的问题是我不确定迭代字符串以提取这些值的最佳方法。 Would rather not use regex library, seems like can be done simply? 宁愿不使用正则表达式库,似乎可以简单地完成?

Use a string stream: 使用字符串流:

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

If there's no final character, the value of optional won't be touched, so I'd recommend setting it to 0 beforehand. 如果没有最终字符,则不会触及optional值,因此我建议事先将其设置为0。

Use std::istringstream , read int, char, int, then try next char: 使用std::istringstream ,读取int,char,int,然后尝试下一个char:

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

I'm not sure this is 100% what you want -but I'd do it in this way. 我不确定这是100%你想要的 - 但我会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM