我尝试在此处/ Google上进行搜索,以找到一种处理我需要处理的输入的最佳方法。这是一个例子...
[1 5 0 50 100 60] [2 4 1 0 40 50]
这些数字是随机的,但我知道事先有多少套括号。另外,我肯定知道格式将始终相同...
用括号括起来的6个数字
我已经在将输入输入一行的地方已经工作了,然后通过字符检查来迭代字符...
1)外循环占括号套的数量
2)首先查看它是否为空格'[',']'
3)如果不是,请获取该号码并存储
4)然后再次开始检查空间
5)存储下一个
6)直到我到达']'并继续循环
但是我觉得需要一种更好/更干净的方式来处理解析。
示例代码...
char c = line[position];
while (c == '[' || c == ']' || cc == ' '){
position++;
c = line[position];
}
string firstStr;
while (c != ' '){
firstStr += c;
position++;
c = line[position];
}
first = atoi(firstStr.c_str());
while (c == ' '){
position++;
ch = line[position];
}
string secondStr;
while (c != ' '){
secondStr += c;
position++;
c = line[position];
}
second = atoi(secondStr.c_str());
是的,我想说这太复杂了,原因很简单,因为C ++库已经包含了此处需要的所有算法的优化实现。
std::string line;
那是你的投入。现在,让我们来分析一下。
#include <algorithm>
auto b=line.begin(), e=line.end();
while ((b=std::find(b, e, '[')) != e)
{
auto n_start=++b;
b=std::find(b, e, ']');
auto your_six_numbers_are_in_here=std::string(n_start, b);
// Now, do whatever you want with your numbers.
}
由于您“确定”您的输入是有效的,因此输入验证的大多数方面不再是问题,并且上面的内容就足够了。
该your_six_numbers_are_in_here
字符串可以包含也可以不包含前导或尾随空格。如何摆脱它们,以及如何提取实际数字是一个单独的任务。现在,由于您“肯定”知道您的输入将是有效的,因此这变得很简单:
std::istringstream i(your_six_numbers_are_in_here);
int a, b, c, d, e, f;
i >> a >> b >> c >> d >> e >> f;
不用说,如果您“不确定”您的输入将是有效的,则需要在此处进行其他工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句