0

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. 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? 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!

Community
  • 1
  • 1
Sciapod
  • 25
  • 4
  • 5
    Looks fine to me. Were you experiencing some sort of problem? Does it not meet your performance requirements? It's very open-ended as to what "help" you're actually seeking here. If I were you I'd just smile at what you've done so far, and move on to the next task in your project. – Lightness Races in Orbit Jun 06 '16 at 18:04

1 Answers1

0

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270