Text File with multiple rows and columns

I completed a intro to C++ course this past fall and I am currently working on an assignment where I have been given the option to use a programing language instead of excel to complete the assignment for my micro-meteorology course. Unfortunately in my C++ course I did not write any programs utilizing text files with multiple rows and columns. The following is an excerpt of the text file I am working with:

1
2
3
4
5
6
Year Mon Day     discharge precipitation  
1980  1  1          46.0    0.00
1980  1  2          39.0    0.00
1980  1  3          30.0    0.00
1980  1  4          25.0    0.00
1980  1  5          23.0    0.00 


The data file includes data for the entire year. I would greatly appreciate anyone's advice on how I can safely extract a whole column at a time and store into an array of the concerned variable in order to preform basic calculations. I feel confident that once I have created the arrays I am comfortable with writing the code to perform the calculations and output the results to a text file.

Best Regards

dbkeith
Last edited on
Assuming you are using an ifstream:
1
2
3
4
5
#include <iostream>

...

  ifstream f( "my input file.txt" );


If the data file has exactly that format, you can just skip one line with:
f.ignore( numeric_limits<streamsize>::max(), '\n' );

then just loop over each row:
1
2
3
4
5
6
  unsigned year, month, day;
  double discharge, precipitation;
  while (f) {
    f >> year >> month >> day >> discharge >> precipitation;
    // (store the data however you like here)
    }


May I suggest using vectors instead of arrays:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <vector>

struct rainfall_t {
  unsigned year, month, day;
  float discharge, precipitation;

  friend istream& operator >> ( istream& ins, rainfall_t& r );
  };

istream& operator >> ( istream& ins, rainfall_t& r ) {
  ins >> r.year >> r.month >> r.day >> r.discharge >> r.precipitation;
  return ins;
  }

...

  vector<rainfall_t> rainfall_data;
  rainfall_t rainfall_datum;

  while (f) {
    f >> rainfall_datum;
    rainfall_data.push_back( rainfall_datum );
    }


Hope this helps.
Last edited on
Topic archived. No new replies allowed.