-1

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 you suggest a way to do this please?

I have to use C++.

Kara
  • 6,115
  • 16
  • 50
  • 57
nagendra
  • 245
  • 6
  • 13

2 Answers2

0

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.

VoronoiPotato
  • 3,113
  • 20
  • 30
  • Thanks Bearder. I could do that but could not read all the data individually. I want to read off each data like a[i][j].May yo suggest me the way please? Thanks. – nagendra Mar 01 '11 at 15:45
0

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 );
   }
}
CashCow
  • 30,981
  • 5
  • 61
  • 92
  • Thanks CashCow. May you tell me how to extract the data from the line[row]? I need my data read in the form of a[i][j]. – nagendra Mar 01 '11 at 15:55
  • 1
    @negendra - Why do you *need* the data in the form `a[i][j]`?? Your question was how to read and multiply two columns of data from a file. Your comments makes it seem more like you are asking SO to do your homework. – Tony Mar 06 '11 at 23:27