简体   繁体   English

从ifstream计算一行中的数据点数

[英]Counting the number of data points in a line from ifstream

I have a bunch of data files I need to read in to some multidimensional container, all of which are of the following form: 我有一堆数据文件需要读入某个多维容器,所有这些容器都具有以下格式:

a1,a2,a3,...,aN,
b1,b2,b3,...,bN,
c1,c2,c3,...,cN,
................
z1,z2,z3,...,zN,

I know from this previous question that a quick way of counting the total number of lines in a file can be achieved as follows: 从上一个问题中我知道可以通过以下方法来快速计算文件中的总行数:

std::ifstream is("filename");
int lines = std::count(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), '\n');

This lets me know what z, the total number of data sets to read in, each of which contains N data points. 这让我知道要读取的数据集总数为z,每个z包含N个数据点。 The next challenge is to count the number of data values per line, for which I can do the following: 下一个挑战是计算每行的数据值数量,对此我可以执行以下操作:

std::ifstream is("filename");
std::string line;
std::getline(is, line);
std::istringstream line_(line);
int points = std::count(std::istreambuf_iterator<char>(line_), std::istreambuf_iterator<char>(), ',');

I can be confident that each file has the same amount of data values per line. 我可以确信每个文件每行具有相同数量的数据值。 My question is, is there a nicer/faster way of achieving the above without resorting to using getline to and dumping a single line to a string? 我的问题是,是否有一种更好/更快的方法来实现上述目标,而又不必使用getline并将单个行转储到字符串中? I was wondering if this could be achieved with stream buffers, but having done a bit of searching it's not quite clear to me. 我想知道是否可以使用流缓冲区来实现,但是经过一些搜索后,对我来说还不是很清楚。

Any help would be much appreciated, thank-you! 任何帮助将不胜感激,谢谢!

If you were required to use 如果需要使用

int points = std::count(std::istreambuf_iterator<char>(line_), std::istreambuf_iterator<char>(), ',');

for every line of text, I would advise you to look for a way to make it more efficient. 对于每行文本,我建议您寻找一种提高效率的方法。

However, you said: 但是,您说:

I can be confident that each file has the same amount of data values per line. 我可以确信每个文件每行具有相同数量的数据值。

That means, you can compute the number points from the first line and assume it to be valid for the rest of the lines. 这意味着,您可以从第一行计算出点数,并假定它对其余行有效。

I wouldn't sweat it for a one time call. 我不会一次打电话就流汗。

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

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