Programming
c++ python parsing string text-files
Updated Fri, 24 Jun 2022 23:43:10 GMT

C++ string parsing (python style)


I love how in python I can do something like:

points = []
for line in open("data.txt"):
    a,b,c = map(float, line.split(','))
    points += [(a,b,c)]

Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas

How can this be done in C++ without too much headache?

Performance is not very important, this parsing only happens one time, so simplicity is more important.

P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,
it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.




Solution

I`d do something like this:

ifstream f("data.txt");
string str;
while (getline(f, str)) {
    Point p;
    sscanf(str.c_str(), "%f, %f, %f\n", &p.x, &p.y, &p.z); 
    points.push_back(p);
}

x,y,z must be floats.

And include:

#include <iostream>
#include <fstream>




Comments (2)

  • +2 – If you decide to change from using floats to using doubles, don't forget to change each %f to %lf. A solution using operator>>() instead of sscanf() doesn't need to be changed in this case. — Feb 14, 2009 at 13:41  
  • +0 – I accepted this answer for brevity and straight-forwardness :) — Feb 17, 2009 at 17:13