using getline() to read from a file
Mar 16, 2016 at 6:49pm UTC
I'm having a problem with the following code. I am using it to read from a file. In the file, there are 83 weather stations that report the name(which is separated from the values by a '\t'), elevation, and then 12 values (which are the amount of precipitation for each month of the year). My program is supposed to gather each value and output the name, elevation, and total rainfall for each month. My program only reads the first weather station for some reason and outputs it 83 times. I don't know how to make it move on to the next value. Any help is greatly appreciated. Thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
float total = 0;
float elevation, precipitation;
string name;
ifstream fin("monthlyPrecipitation.txt" );
//ofstream fout("annualPrecipitation.txt");
if (!fin) {
cout << "Error opening file. Shutting down..." << endl;
return 0;
}
cout << "Annual Precipitation Report" << endl << endl;
cout << "Weather Station\tElevation\tPrecipitation" << endl;
for (int i = 0; i <= 83; i++) {
getline(fin, name, '\t' );
fin >> elevation;
fin.ignore();
for (int j = 0; j <= 12; j++) {
fin >> precipitation;
total += precipitation;
}
cout << name << "\t" << elevation << "\t" << total << endl;
}
cout << endl;
return 0;
}
Mar 17, 2016 at 3:22am UTC
Hey! I'm having the exact same issue! Did you figure it out??
Mar 17, 2016 at 9:39am UTC
step through the debugger so you can follow the sequence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream fin("c:/temp/monthlyPrecipitation.txt" );
//ofstream fout("annualPrecipitation.txt");
if (!fin)
{
cout << "Error opening file. Shutting down..." << endl;
return 0;
}
cout << "Annual Precipitation Report" << endl << endl;
cout << "Weather Station\tElevation\tPrecipitation" << endl;
int counter = 0;
float total = 0;
float precipitation = 0;
string name;
// get current line
for ( std::string line; getline( fin, line ,'\n' ); )
{
// store current line in a stream
stringstream ss(line);
// parse current line
for (std::string current; getline(ss,current,'\t' );)
{
counter++;
if (counter == 3)
{
// store in a stream to convert to a number
stringstream data(current);
total = 0;
// sum up values
for ( int i=0; i < 12; i++)
{
data >> precipitation;
total += precipitation;
}
cout << total;
counter = 0;
}
else
{
// output data
cout << current << '\t' ;
}
}
cout << '\n' ;
}
cout << endl;
return 0;
}
Topic archived. No new replies allowed.