在带括号的字符串中拆分参数
splitting parameters in a string with parenthesis
我想找到一种有效的方法来拆分这种字符串并将参数存储在变量中:
param1 (param2 param3) (param4 param5) ... param6
例:
1. (10 10) (10 15) (2 11) 2.
1. (12 20) 2.
(有一个未定义的括号,每 2 个数字用空格分隔)
我必须将第一个和最后一个参数存储在双精度中,并将数字存储在向量中的括号中。
对于第二个示例,它将给出:
double beginOfLine, endOfLine
vector<int> vec1;
vector<int> vec2;
beginOfLine = 1.;
endOfLine = 2.;
vec1.push_back(12);
vec2.push_back(20);
我发现在python中很容易。但C++我无法以简单的方式做到这一点。
注意:我不允许使用 boost/C++11 及更高版本
由于您不能使用 C++11,因此使用std::stringstream
进行一些基本的字符串拆分可能会完成这项工作。我不确定<limits>
何时是 C++11 的一部分,但您可以轻松地用另一个最大值替换它们。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <limits>
int main()
{
double beginOfLine = 0.0, endOfLine = 0.0;
std::vector<int> vec1;
std::vector<int> vec2;
std::stringstream ss("1. (10 10) (10 15) (2 11) 2.");
ss >> beginOfLine;
while (true) {
int first, second;
ss.ignore(std::numeric_limits<std::streamsize>::max(), '(');
ss >> first >> second;
vec1.push_back(first);
vec2.push_back(second);
ss.ignore(std::numeric_limits<std::streamsize>::max(), ')');
ss.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
if (ss.peek() != '(') {
ss >> endOfLine;
break;
}
}
std::cout << beginOfLine << 'n';
for (std::vector<int>::iterator it = vec1.begin(); it != vec1.end(); ++it)
std::cout << *it << ' ';
std::cout << 'n';
for (std::vector<int>::iterator it = vec2.begin(); it != vec2.end(); ++it)
std::cout << *it << ' ';
std::cout << 'n' << endOfLine;
return 0;
}
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 使用 C++ 将命令行参数拆分为参数/向量
- 在带括号的字符串中拆分参数
- Doxygen,当参数类型定义使签名相同时,如何拆分函数文档?
- 拆分参数包
- 根据函数指针参数拆分多个可变参数模板包
- 如何使用 c++ 逐行处理文本文件并将其参数拆分为变量?
- 在预处理器中拆分参数C++
- 如何在各个参数中拆分#__VA_ARGS__
- 按给定类型拆分参数包
- 拆分64位值以适应双精度参数类型
- 在c++ /Qt中拆分Lua函数调用的混合字符串/数字参数列表
- 取消对拆分函数调用参数的信任