简体   繁体   English

如何从具有可变长度数字的字符串中提取多个数字

[英]How to extract multiple numbers from a string with numbers of variable length

We have a string which consists of "RESERVE number1,number2,number3,number4" , where number1,number2,number3 and number4 can be any number from 0 to 10, without decimal point.我们有一个由"RESERVE number1,number2,number3,number4"组成的字符串,其中 number1,number2,number3 和 number4 可以是 0 到 10 之间的任意数字,不带小数点。

The string's format cannot be changed, and we want to extract each of those numbers into their respective int variables.字符串的格式无法更改,我们希望将这些数字中的每一个提取到它们各自的 int 变量中。

We have tried, so far, to:到目前为止,我们已经尝试过:

  • Use substr , alongside find , but in order to use find again, we may have to remove the "matched part" of the string from the original one, and we are not sure on how to do thatfind旁边使用substr ,但为了再次使用 find ,我们可能必须从原始字符串中删除字符串的“匹配部分”,我们不确定如何做到这一点

  • Use stoi , but then we have the same problem as before.使用stoi ,但是我们遇到了和以前一样的问题。 Most examples we have seen make use of stoi, but always in cases where there is only one numeric value in the string, not multiple ones.我们看到的大多数示例都使用了 stoi,但总是在字符串中只有一个数值而不是多个数值的情况下。

Any ideas are welcome!欢迎任何想法!

Use sscanf.使用 sscanf。 Example:例子:

int num1, num2, num3, num4;
std::string s = "RESERVE 11,22,33,44";
sscanf(s.c_str(), "RESERVE %d,%d,%d,%d", &num1, &num2, &num3, &num4); 

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

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