c ++文件io&分隔符分割 [英] c++ file io & splitting by separator

查看:169
本文介绍了c ++文件io&分隔符分割的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  0,2,10 
10,8, 10
10,10,10 $ b $ 10,16,10
15,10,16
17,10,16
$ / code> pre>

我希望能够输入文件并将其分成三个数组,在这个过程中修剪所有多余的空格并将每个元素转换为整数。



出于某种原因,我找不到一个简单的方法来做到这一点在c + +。我得到的唯一成功是将每行输入到一个数组中,然后重新排列所有空格,然后将其分开。这整个过程花了我20-30行的代码,并痛苦地修改说另一个分隔符(如空间)等。

这是python相当于我想在C ++中有什么:

  f = open('input_hard.dat')
lines = f.readlines()
f.close()

#declarations
inint,inbase,outbase = [],[],[]

#input parsing
for line in line:
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行代码。

任何帮助将不胜感激,谢谢! / p>

解决方案

fscanf确实没有错,这可能是这种情况下最快的解决方案。它和Python代码一样简洁易读:

  FILE * fp = fopen(file.dat,r ); 
int x,y,z;
std :: vector< int> vx,vy,vz; (fscanf(fp,%d,%d,%d,& x,& y,& z)== 3){
vx.push_back(

X);
vy.push_back(y);
vz.push_back(z);
}
fclose(fp);


I have a file with data listed as follows:

0,       2,    10
10,       8,    10
10,       10,   10
10,       16,   10
15,       10,   16
17,       10,   16

I want to be able to input the file and split it into three arrays, in the process trimming all excess spaces and converting each element to integers.

For some reason I can't find an easy way to do this in c++. The only success I've had is by inputting each line into an array, and then regexing out all the spaces and then splitting it up. This entire process took me a good 20-30 lines of code and its a pain to modify for say another separator(eg. space), etc.

This is the python equivalent of what I would like to have in C++:

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()))

The ease of use of doing this in python is one of the reasons why I moved to it in the first place. However, I require to do this in C++ now and I would hate to have to use my ugly 20-30 line code.

Any help would be appreciated, thanks!

解决方案

There is really nothing wrong with fscanf, which is probably the fastest solution in this case. And it's as short and readable as the python code:

FILE *fp = fopen("file.dat", "r");
int x, y, z;
std::vector<int> vx, vy, vz;

while (fscanf(fp, "%d, %d, %d", &x, &y, &z) == 3) {
  vx.push_back(x);
  vy.push_back(y);
  vz.push_back(z);
}
fclose(fp);

这篇关于c ++文件io&amp;分隔符分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆