Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string parsing (python style)

Tags:

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.

like image 215
hasen Avatar asked Feb 11 '09 09:02

hasen


People also ask

How do you use %s in Python?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.

Is there a scanf () or sscanf () equivalent in Python?

The scanf () method in Python Python does not currently have a sscanf() equivalent. Regular expressions are generally more powerful, albeit more verbose, than scanf () strings. The table below shows some more or less equivalent mappings between scanf () format tokens and regular expressions.

How do you parse a string in Python?

Parse String to List With the str. split() function to split the string on the basis of each , . The str. split() function takes a delimiter/separator as an input parameter, splits the calling string based on the delimiter, and returns a list of substrings.

How do you convert strings to C in Python?

foo("string") passes a Python str object to a C function which will later assign the string to char *c_ptr .


1 Answers

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>
like image 170
klew Avatar answered Oct 12 '22 01:10

klew