C++ string parsing (python style)

后端 未结 10 1157
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 07:52

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


        
10条回答
  •  粉色の甜心
    2020-12-08 08:30

    This answer is based on the previous answer by j_random_hacker and makes use of Boost Spirit.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    using namespace boost;
    using namespace boost::spirit;
    
    struct Point {
        double a, b, c;
    };
    
    int main(int argc, char **argv) 
    {
        vector points;
    
        ifstream f("data.txt");
    
        string str;
        Point p;
        rule<> point_p = 
               double_p[assign_a(p.a)] >> ',' 
            >> double_p[assign_a(p.b)] >> ',' 
            >> double_p[assign_a(p.c)] ; 
    
        while (getline(f, str)) 
        {
            parse( str, point_p, space_p );
            points.push_back(p);
        }
    
        // Do something with points...
    
        return 0;
    }
    

提交回复
热议问题