i'm working on a project for school where i have a file in the format:
string
double,double,double,double,double,double,double
double,double,double,double,double,double,double
double,double,double,double,double,double,double
double,double,double,double,double,double,double
where string is a month and the doubles are temperatures of each day of the month
the months are fake months that all have 28 days, so the set up is literally like that regardless of the month
i need to read this file, then print to a new file the highest temperature, lowest temp, average weekly temp, and average monthly temp
for(int i=0; i<28; i++)
{
/*here i would like to scan for the next double*/
}
}
weatherFile.close ();
newFile.close ();
}
return 0;
}
also, here is what the text file weatherData looks like:
February
68,69,62,69,74,79,72
77,76,76,78,82,78,74
76,78,82,80,76,78,81
79,82,78,85,77,79,82
March
82,86,82,85,76,80,80
83,84,83,90,87,86,83
83,84,84,83,82,84,80
84,82,80,78,81,83,77
well, you can convert syour string to a null-terminated string and use strtok() function,
or you can use stringstreams and getline(/*sstream*/, /*string*/, ';') (Or take it directly from cin)
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream weather_file( "weatherData.txt" ) ; // open the file
// for each month
{
// read the month
std::string month ;
std::getline( weather_file, month ) ;
double temperatures[28] ;
// repeat four times, one for each line of seven doubles
for( int i = 0 ; i < 4 ; ++i )
{
// read the first six doubles, throwing away the comma after each one
char comma ;
for( int j = 0 ; j < 6 ; ++i ) weather_file >> temperatures[ i*7 + j ] >> comma ;
// read the seventh double
weather_file >> temperatures[ i*7 + 6 ] ;
}
// before attempting to read another month,
// throw away the newline at the end of the last line
weather_file.ignore( 1000, '\n' ) ;
}
}
There is a typo in this line: for( int j = 0 ; j < 6 ; ++i /*typo*/ ) weather_file >> temperatures[ i*7 + j ] >> comma ;
Change it to: for( int j = 0 ; j < 6 ; ++j /*corrected*/ ) weather_file >> temperatures[ i*7 + j ] >> comma ;
EDIT:
> after compiling, but it never normally does that....
You are running this on a Windows platform, where status -107374181 is an access violation; ie. you attempted to access an invalid area of memory. An immediate crash is the best thing that can happen if you do that.
thanks! but i need it to print to a new file the lowest temperature & highest temperature of each month, the average temperature of each week,and then the average temperature of each month
> but i need it to print to a new file the lowest temperature & highest temperature of each month,
> the average temperature of each week,and then the average temperature of each month
Ok. Now that you are able to read in the data, start working on the code to process that data and write out the results to another file.