我有一个包含如下数据的文件:
0, 2, 10
10, 8, 10
10, 10, 10
10, 16, 10
15, 10, 16
17, 10, 16
我希望能够输入文件并将其拆分为三个数组,在此过程中修剪所有多余的空间并将每个元素转换为整数。
出于某种原因,我找不到在 C++ 中执行此操作的简单方法。我取得的唯一成功是将每一行输入到一个数组中,然后对所有空格进行正则表达式,然后将其拆分。整个过程花了我 20-30 行代码,修改另一个分隔符(例如空格)等很痛苦。
这是我希望在 C++ 中拥有的 python 等价物:
f = open('input_hard.dat')
lines = f.readlines()
f.close()
#declarations
inint, inbase, outbase = [], [], []
#input parsing
for line in lines:
bits = string.split(line, ',')
inint.append(int(bits[0].strip()))
inbase.append(int(bits[1].strip()))
outbase.append(int(bits[2].strip()))
在 python 中执行此操作的易用性是我首先转向它的原因之一。但是,我现在需要在 C++ 中执行此操作,而且我不愿意使用丑陋的 20-30 行代码。
任何帮助将不胜感激,谢谢!
最佳答案
在这个例子中没有真正需要使用 boost,因为流可以很好地完成这个技巧:
int main(int argc, char* argv[])
{
ifstream file(argv[1]);
const unsigned maxIgnore = 10;
const int delim = ',';
int x,y,z;
vector<int> vecx, vecy, vecz;
while (file)
{
file >> x;
file.ignore(maxIgnore, delim);
file >> y;
file.ignore(maxIgnore, delim);
file >> z;
vecx.push_back(x);
vecy.push_back(y);
vecz.push_back(z);
}
}
虽然如果我要使用 boost,我更喜欢 tokenizer 的简单性正则表达式... :)
关于C++文件IO和分隔符拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/267427/