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

后端 未结 2 1991
天涯浪人
天涯浪人 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: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 >

    ifstream ifs( filename );
    std::vector< std::vector< double > > mat;
    if( ifs.is_open() )
    {
       std::string line;
       while( std::getline( ifs, line ) )
       {
           std::vector values;
           std::istringstream iss( line );
           double val;
           while( iss >> val )
           {
              values.push_back( val );
           }
           mat.push_back( values );
       }
    }
    

提交回复
热议问题