我有这个格式的字符串:我怎样才能提取值对从C++字符串
"name1":1234 " name2 " : 23456 "name3" : 12345
等等...
我曾尝试使用嵌套while循环和两个整数存储在string::substr
中使用的位置和长度,但我找不到一个合适的方式来获取它(大多数时候我最终从字符串中结束)。
这些值不需要存储,因为我可以调用一个函数来处理它们,只要我得到它们。
这是我迄今所做的:提前
void SomeClass::processProducts(std::string str) {
unsigned int i = 0;
std::string name;
while (i < str.length()) {
if (str[i] == '\"') {
int j = 1;
while (str[i + j] != '\"') {
j++;
}
name = str.substr(i + 1, j - 1);
i += j;
}
else if (str[i] >= '0' && str[i] <= '9') {
int j = 1;
while (str[i + j] >= '0' && str[i + j] <= '9') {
j++;
}
//This is just processes the values
std::stringstream ss;
std::string num = str.substr(i, j);
ss.str(num);
int products = 0;
ss >> products;
if (products == 0) {
Util::error(ERR_WRONG_PRODUCTS);
}
int pos = getFieldPos(name);
if (pos == -1) {
Util::error(ERR_WRONG_NAME);
}
else {
fields[pos].addProducts(products);
}
i += j;
}
i++;
}
}
感谢。
欢迎堆栈溢出。请花些时间阅读[The Tour](http://stackoverflow.com/tour),并参阅[帮助中心](http://stackoverflow.com/help/asking)中的资料,了解您可以在这里问。 –
请[编辑]您的问题,以显示您尝试过的并不适合您的实际代码。到目前为止,你自己调试过什么? –
你想得到什么结果?例如,你想从“name1”中得到什么? –