How to read numbers from an ASCII file (C++)

后端 未结 4 1677
梦如初夏
梦如初夏 2021-01-31 19:48

I need to read in data files which look like this:

* SZA: 10.00
 2.648  2.648  2.648  2.648  2.648  2.648  2.648  2.649  2.650  2.650
 2.652  2.653  2.652  2.653         


        
4条回答
  •  天涯浪人
    2021-01-31 20:46

    Simple solution using STL algorithms:

    #include 
    #include 
    #include 
    #include 
    
    struct data
    {
       float first; // in case it is required, and assuming it is 
                    // different from the rest
       std::vector values;
    };
    
    data read_file( std::istream& in )
    {
       std::string tmp;
       data d;
       in >> tmp >> tmp >> d.first;
       if ( !in ) throw std::runtime_error( "Failed to parse line" );
    
       std::copy( std::istream_iterator( in ), std::istream_iterator(),
             std::back_inserter(d.values) );
    
       return data;
    }
    

    If you really need to use an array, you must first allocate it (either dynamically or statically if you know the size) and then you can use the same copy algorithm

    // parsing the first line would be equivalent
    float data[128]; // assuming 128 elements known at compile time
    std::copy( std::istream_iterator(is), std::istream_iterator(), 
          data );
    

    But I would recommend using std::vector even in this case, if you need to pass the data into a function that takes an array you can always pass it as a pointer to the first element:

    void f( float* data, int size );
    int main()
    {
       std::vector v; // and populate
       f( &v[0], v.size() ); // memory is guaranteed to be contiguous
    }
    

提交回复
热议问题