Read data from a file individually and multiply the two columns in C++

后端 未结 2 1898
天涯浪人
天涯浪人 2021-01-17 06:10

I have a data file \"1.dat\" which has 4 columns and 250 rows.

I need to read each row and process it such as to multiply two columns [col1 and col2].

Can yo

相关标签:
2条回答
  • 2021-01-17 06:20

    http://www.cplusplus.com/doc/tutorial/files/ Here's a few tips on how to read a file using C++, after that you're going to need to cast a string into an integer or float depending.

    0 讨论(0)
  • 2021-01-17 06:40

    Assuming the file has delimited data, you will probably:

    • use ifstream to open the file
    • use std::getline( ifstream, line ) to read a line. You can do this in a loop. line should be of type std::string
    • process each line using istringstream( line ) then reading these into your element.

    To store the read data you could use vector< vector< double > > or some kind of matrix class.

    with vector<vector<double> >

    ifstream ifs( filename );
    std::vector< std::vector< double > > mat;
    if( ifs.is_open() )
    {
       std::string line;
       while( std::getline( ifs, line ) )
       {
           std::vector<double> values;
           std::istringstream iss( line );
           double val;
           while( iss >> val )
           {
              values.push_back( val );
           }
           mat.push_back( values );
       }
    }
    
    0 讨论(0)
提交回复
热议问题