C++ string parsing (python style)

后端 未结 10 1135
伪装坚强ぢ
伪装坚强ぢ 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:39

    #include 
    #include 
    #include 
    #include 
    #include 
    #include      // For replace()
    
    using namespace std;
    
    struct Point {
        double a, b, c;
    };
    
    int main(int argc, char **argv) {
        vector points;
    
        ifstream f("data.txt");
    
        string str;
        while (getline(f, str)) {
            replace(str.begin(), str.end(), ',', ' ');
            istringstream iss(str);
            Point p;
            iss >> p.a >> p.b >> p.c;
            points.push_back(p);
        }
    
        // Do something with points...
    
        return 0;
    }
    

提交回复
热议问题