C++ string parsing (python style)

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

    Its nowhere near as terse, and of course I didn't compile this.

    float atof_s( std::string & s ) { return atoi( s.c_str() ); }
    { 
    ifstream f("data.txt")
    string str;
    vector<vector<float>> data;
    while( getline( f, str ) ) {
      vector<float> v;
      boost::algorithm::split_iterator<string::iterator> e;
      std::transform( 
         boost::algorithm::make_split_iterator( str, token_finder( is_any_of( "," ) ) ),
         e, v.begin(), atof_s );
      v.resize(3); // only grab the first 3
      data.push_back(v);
    }
    
    0 讨论(0)
  • 2020-12-08 08:39
    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    #include <vector>
    #include <algorithm>     // For replace()
    
    using namespace std;
    
    struct Point {
        double a, b, c;
    };
    
    int main(int argc, char **argv) {
        vector<Point> 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;
    }
    
    0 讨论(0)
  • 2020-12-08 08:40

    all these are good examples. yet they dont answer the following:

    1. a CSV file with different column numbers (some rows with more columns than others)
    2. or when some of the values have white space (ya yb,x1 x2,,x2,)

    so for those who are still looking, this class: http://www.codeguru.com/cpp/tic/tic0226.shtml is pretty cool... some changes might be needed

    0 讨论(0)
  • 2020-12-08 08:47

    One of Sony Picture Imagework's open-source projects is Pystring, which should make for a mostly direct translation of the string-splitting parts:

    Pystring is a collection of C++ functions which match the interface and behavior of python’s string class methods using std::string. Implemented in C++, it does not require or make use of a python interpreter. It provides convenience and familiarity for common string operations not included in the standard C++ library

    There are a few examples, and some documentation

    0 讨论(0)
提交回复
热议问题