Hey, I need a little bit of help figuring out how to find the minimum and maximum of a particular data in a file. Should I treat the file I'm opening as an Array in order to find it or is there a certian function that can do this?

Recommended Answers

All 38 Replies

Hey, I need a little bit of help figuring out how to find the minimum and maximum of a particular data in a file. Should I treat the file I'm opening as an Array in order to find it or is there a certain function that can do this?

I'd say you have to read the file contents that you are interested in into a variable or variables, and use whatever algorithm you want to find the max and min. I know of no way to do it directly with the file without using an ifstream to read from the file into variables. Depending on your needs, you may not need an array in order to find the max and min. Unless there is a need to, I wouldn't bother storing all the numbers in the file. Set up two variables, max and min, then read from the file one number at a time. If a number is read in from the file that is smaller than the min or larger than the max, assign the min or max to be that number.

But as far as some function existing that reads through a file and finds the minimum and maximum for you, I know of no such function. Of course, that doesn't mean such a function doesn't exist, but I don't know of one.

Heh heh heh....

You're going to love this:

#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>

using namespace std;

int main()
  {
  string filename;
  cout << "Enter the numbers filename> ";
  getline( cin, filename );

  ifstream file( filename.c_str() );
  if (!file)
    {
    cout << "Invalid filename.\n";
    return EXIT_FAILURE;
    }

  istream_iterator<int> max_begin( file ), max_end;
  istream_iterator<int> min_begin( file ), min_end;

  int max = *max_element( max_begin, max_end );

  file.clear();
  file.seekg( 0 );

  int min = *min_element( min_begin, min_end );

  cout << "The largest number in the file is "  << max << endl;
  cout << "The smallest number in the file is " << min << endl;

  file.close();

  return EXIT_SUCCESS;
  }

Enjoy!

[edit] Oh yeah, here is my numbers file:

12
-7
108
43

Heh heh heh....

You're going to love this:

#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>

using namespace std;

int main()
  {
  string filename;
  cout << "Enter the numbers filename> ";
  getline( cin, filename );

  ifstream file( filename.c_str() );
  if (!file)
    {
    cout << "Invalid filename.\n";
    return EXIT_FAILURE;
    }

  istream_iterator<int> max_begin( file ), max_end;
  istream_iterator<int> min_begin( file ), min_end;

  int max = *max_element( max_begin, max_end );
  int min = *min_element( min_begin, min_end );

  cout << "The largest number in the file is "  << max << endl;
  cout << "The smallest number in the file is " << min << endl;

  file.close();

  return EXIT_SUCCESS;
  }

Enjoy!

[edit] Oh yeah, here is my numbers file:

12
-7
108
43

Ha! Didn't work! Here's MY numbers file.

5 3 1 8 6 2 5 9

It correctly identified 9 as the largest, but picked 3 as the smallest. It worked on your set though, and since it found the 9 on mine, I'm going to give you rep points. ;)

Sorry, it is a limitation of stream iterators. I forgot to reset the file between max and min. I repaired my post above so that it will work correctly now.

BTW. Thanks Vernon.

I was kind of hoping to get another cookie from Narue for this... :S

Well Perhaps I should've been more precise with my reuqest. Basically I'm supposed to anylize the daily maximum and minimum of Temperature, Pressure and Humidity from a file that a user chooses by typing the file name into a prompt after choosing it in a menu. I'm also supposed to find out the maximum daily wind speed as well.

Well Here's my code so far

///
///
///
///
///
/// Program: Weather data processing
/// Created by: Wesley Montgomery
/// This program anlizes weather data accessed from a file and finds the average of Temperature, Humidity, and other facts.
///
///
///

#include <fstream>	
#include <iostream>
#include <string>
#include <cmath>
#include <stdlib.h>

#define MAX_SIZE 4589

using namespace std;

int main()
{ 
	int pressure, temp, windspeed, windchill, dew, heatindx, humidity, rainfall, winddir, avgwindspeed, peakwindspeed, totalrainfall;
	bool  done; // exit flag 
	char  selection; //Menu Selection
	string file; // Name of datafile
	ifstream weatherfile; //datafile stream


	// Initialize exit flag
	 done = false;

	while (!done) 
	{
		// Output menu list
		cout << "\n\n";
		cout << "************************\n\n";		
		cout << "  Weather Data Analysis: \n";		
		cout << "  1) Select Data File to be loaded\n";		
		cout << "  2) Daily Min/max of Temp,Pressure and humidity\n";		
		cout << "  3) Daily Max Wind Speed\n";		
		cout << "  4) Avg Pressure, Humidity, and Windspeed for rainy days\n";	
		cout << "  5) Total Daily Rainfall\n";
		cout << "  6) Exit Program\n";
		cout << "************************\n\n";		

		// Input data					
		cout << "Selection -> ";		
		cin >> selection;
		cout << "\n\n";

		// Process input
		if (selection=='1') 
		{
			cout << "Insert Data file:";
			cin >> file; 
			weatherfile.open (file.c_str(), ios::in);
			cout << "\n\n";
		}
		else if (selection=='2')
		{
			while (!weatherfile.eof())
			{
			}
		}
		else if (selection=='3')
		{
			while (!weatherfile.eof())
			{
			}
			
		}
		else if (selection=='4')
		{
			while (!weatherfile.eof())
			{
			if (rainfall > 0)
			{ 
			}
			}
			
		}
		else if (selection=='5')
		{
			while (!weatherfile.eof())
			{
			}
		}
		else if (selection=='6')
		{
			cout << "Goodbye. Thank you for using my program.\n\n";
			done = true;					// flag for exit
		}
		else
		{
			cout << "** Invalid Selection. **\n\n";
		}

	} // end of while loop

	return (0);
}

And here's an example of the file it's supposed to open.

DATE,HOUR,Temperature,Wind Chill,Dew Point,Heat Index,Relative Humidity,Pressure,RainFall,Wind Dir,Wind Speed,Avg. Wind Spd.,Peak Wind Spd.
07/01/1999,11:30,53,53,51,53,92,1014,0.00,180,0,0,0
07/01/1999,11:40,54,54,50,54,87,1014,0.03,225,0,1,5
07/01/1999,11:50,56,54,50,56,81,1015,0.03,180,5,1,5
07/01/1999,12:00,57,57,52,57,83,1014,0.03,270,0,0,2
07/01/1999,12:10,57,52,49,57,76,1015,0.04,292,7,4,7
07/01/1999,12:20,58,58,53,58,83,1015,0.06,315,3,2,4
07/01/1999,12:30,58,58,53,58,83,1015,0.06,337,0,2,5
07/01/1999,12:40,59,59,52,59,77,1015,0.08,270,2,3,4
07/01/1999,12:50,60,60,53,60,78,1015,0.09,360,0,1,4
07/01/1999,13:00,60,60,53,60,78,1015,0.12,360,0,1,4
07/01/1999,13:10,61,54,48,61,62,1014,0.12,247,10,4,10
07/01/1999,13:20,62,62,47,62,59,1015,0.12,180,3,3,7
07/01/1999,13:30,62,62,49,62,62,1015,0.12,247,1,3,7
07/01/1999,13:40,62,62,48,62,60,1015,0.12,225,4,3,6
07/01/1999,13:50,64,64,49,64,58,1014,0.14,180,4,1,5
07/01/1999,14:00,65,65,46,62,51,1015,0.14,202,4,5,9

And Well I'm also getting errors with this code of mine that mostly say 'unreferenced local variable even though they are there in the int list at the top. I tried find some solutions in my book, but it didn't help that much. I also tried to find information on the internet but I didn't have any luck there as well.
So could someone help me with this little problem?

Sorry for the double post but I'm not asking for someone to do the work for me, I just need a little bit of help figuring out how to do it, if someone could just perhaps nudge me in the right direction by maybe explaining to me how to do it that then I could do the rest of it no problem.

well i think to find the highest and lowest you could read it into an array and find the highest and lowest..i.e

infile>>myArray[i];

then you play you can find the highest and lowest

And Well I'm also getting errors with this code of mine that mostly say 'unreferenced local variable even though they are there in the int list at the top. I tried find some solutions in my book, but it didn't help that much. I also tried to find information on the internet but I didn't have any luck there as well.
So could someone help me with this little problem?

ureferenced local variable refers to variables that have been declared and not used..it is just a warning from the compiler...in your case, you have declared "heatindx", "avgwindspeed" etc without using them...look at your declarations

Argh.

OK. You are parsing a standard CSV file, with a header record.

Handle it thus:

#include <algorithm>  // for min() and max()
#include <fstream>
#include <sstream>
#include <string>

ifstream csvfile( "foo.csv" );
if (!csvfile)
  {
  complain();
  return;
  }

string target_date = "07/01/1999";

string record;

// skip the header record
getline( csvfile, record );

// examine all remaining records
unsigned record_number = 0;
while (getline( csvfile, record ))
  {
  stringstream fields( record );
  string field;
  for (unsigned field_number = 0; getline( fields, field, ',' ); field_number++)
    switch (field_number)
      {
      case 0:
        if (field != target_date) goto l_next_record; // valid!
        break;

      case 1:  // we don't care what hour for avg, min, or max of anything
        break;

      case 2:
        // Convert the field to a number (complain if it isn't)
        int temperature;
        if (!(stringstream( field ) >> temperature))
          {
          complain();
          break;
          }
        // If this is the very first record, initialize our min and max
        if (record_number == 0)
          {
          min_temperature := temperature;
          max_temperature := temperature;
          }
        min_temperature := min( min_temperature, temperature );
        max_temperature := max( max_temperature, temperature );
        break;

      case ...
      }
  l_next_record:
  record_number++;
  }

csvfile.close();

Hope this helps.

Hey Duoas, I tried to do what you did but:
fatal error C1903: unable to recover from previous error(s); stopping compilation

And the file I am getting the data from is a text file and here's my code as it was when I asked the question

///
///
///
///
///
/// Program: Weather data processing
/// Created by: Wesley Montgomery
/// This program anlizes weather data accessed from a file and finds the average of Temperature, Humidity, and other facts.
///
///
///

#include <fstream>	
#include <iostream>
#include <string>
#include <cmath>
#include <stdlib.h>
#include <algorithm>  // for min() and max()
#include <sstream>

#define MAX_SIZE 4589

using namespace std;

int main()
{ 
	int pressure, temp, windspeed, humidity, rainfall, avgwindspeed, peakwindspeed, totalrainfall;
	bool  done; // exit flag 
	char  selection; //Menu Selection
	string file; // Name of datafile
	ifstream weatherfile; //datafile stream


	// Initialize exit flag
	 done = false;

	while (!done) 
	{
		// Output menu list
		cout << "\n\n";
		cout << "************************\n\n";		
		cout << "  Weather Data Analysis: \n";		
		cout << "  1) Select Data File to be loaded\n";		
		cout << "  2) Daily Min/max of Temp,Pressure and humidity\n";		
		cout << "  3) Daily Max Wind Speed\n";		
		cout << "  4) Avg Pressure, Humidity, and Windspeed for rainy days\n";	
		cout << "  5) Total Daily Rainfall\n";
		cout << "  6) Exit Program\n";
		cout << "************************\n\n";		

		// Input data					
		cout << "Selection -> ";		
		cin >> selection;
		cout << "\n\n";

		// Process input
		if (selection=='1') 
		{
			cout << "Insert Data file:";
			cin >> file; 
			weatherfile.open (file.c_str(), ios::in);
			cout << "\n\n";
		}
		else if (selection=='2')
		{
			while (!weatherfile.eof())
			{
			}
		}
		else if (selection=='3')
		{
			while (!weatherfile.eof())
			{
			}
			
		}
		else if (selection=='4')
		{
			while (!weatherfile.eof())
			{
			if (rainfall > 0)
			{ 
			}
			}
			
		}
		else if (selection=='5')
		{
			while (!weatherfile.eof())
			{
			}
		}
		else if (selection=='6')
		{
			cout << "Goodbye. Thank you for using my program.\n\n";
			done = true;					// flag for exit
		}
		else
		{
			cout << "** Invalid Selection. **\n\n";
		}

	} // end of while loop

	return (0);
}

Now is there any problems with this skeketon of a code that makes what you suggested not work?

Hey Duoas, I tried to do what you did but:
fatal error C1903: unable to recover from previous error(s); stopping compilation


Now is there any problems with this skeketon of a code that makes what you suggested not work?

Duoas didn't give you a full functioning program. There is no main function, nor is there a complain() function, so it's not going to compile. Also, you'll probably have to change := in his code to = (may depend on the compiler, there may be a compiler he is using that accepts := ). If you tried to compile Duoas's code exactly as he listed it, it's not going to work. You have to take some of it and execute it in your option 2 (finding min and max) code block.

Oops! I switch between C++ and Delphi a lot... so those := s should be = s... (sorry :$ )

You will also have to do the following after each time you look through the entire file:

weatherfile.clear();
weatherfile.seekg( 0 );

That turns off the EOF bit (which would prevent further attempts to read the file) and resets the read pointer to the beginning of the file.

BTW, is this homework? (Because if it isn't I can show you something that will make organizing your program much easier, but it is pretty advanced so if it is homework your teacher won't like it and I'll suggest something else.)

Yes Duoas this is homework, which is why I said in a earlier post that I don't want the work done for me just maybe an explination or a little bit of help to make my program work.

Btw here's what I have so far in my code

///
///
///
///
///
/// Program: Weather data processing
/// Created by: Wesley Montgomery
/// This program anlizes weather data accessed from a file and finds the average of Temperature, Humidity, and other facts.
///
///
///

#include <fstream>	
#include <iostream>
#include <string>
#include <cmath>
#include <stdlib.h>
#include <algorithm>  // for min() and max()
#include <sstream>

#define MAX_SIZE 4589

using namespace std;

int main()
{ 
	int pressure, temp, windspeed, humidity, rainfall, peakwindspeed, min_temp, max_temp, totalrainfall;
	bool  done; // exit flag 
	char  selection; //Menu Selection
	string file; // Name of datafile
	ifstream weatherfile; //datafile stream


	// Initialize exit flag
	 done = false;

	while (!done) 
	{
		// Output menu list
		cout << "\n\n";
		cout << "************************\n\n";		
		cout << "  Weather Data Analysis: \n";		
		cout << "  1) Select Data File to be loaded\n";		
		cout << "  2) Daily Min/max of Temp,Pressure and humidity\n";		
		cout << "  3) Daily Max Wind Speed\n";		
		cout << "  4) Avg Pressure, Humidity, and Windspeed for rainy days\n";	
		cout << "  5) \n";
		cout << "  6) Exit Program\n";
		cout << "************************\n\n";		

		// Input data					
		cout << "Selection -> ";		
		cin >> selection;
		cout << "\n\n";

		// Process input
		if (selection=='1') 
		{
			cout << "Insert Data file:";
			cin >> file; 
			weatherfile.open (file.c_str(), ios::in);
			cout << "\n\n";
		}
		else if (selection=='2')
		{
			while (!weatherfile.eof())
			{
				string target_date = "04/18/2008";
 
                 string record;
 
              // skip the header record
              getline( weatherfile, record );
 
           // examine all remaining records
             unsigned record_number = 0;
             while (getline( weatherfile, record ))
                {
             stringstream fields( record );
              string field;
          for (unsigned field_number = 0; getline( fields, field, ',' ); field_number++)
               switch (field_number)
		  {
               case 0:
               if (field != target_date) goto l_next_record; // valid!
              break;
 
                case 1:  // we don't care what hour for avg, min, or max of anything
               break;
 
              case 2:
                // Convert the field to a number (complain if it isn't)
                int temp;
              if (!(stringstream( field ) >> temp))
             {
               cout << "Not a Temperature." << endl;
               break;
            }
           // If this is the very first record, initialize our min and max
           if (record_number == 0)
             {
            min_temp = temp;
            max_temp = temp;
             }
         min_temp = min( min_temp, temp);
         max_temp = max( max_temp, temp);
         break;
		  }
       l_next_record:
       record_number++;
			 }
			 cout << "The Maximum Temperature is" << max_temp << "degrees." << endl;
			 cout << "The Minimum Temperature is" << min_temp << "degrees." << endl;
 
			}
		}
		else if (selection=='3')
		{
			while (!weatherfile.eof())
			{
			}
			
		}
		else if (selection=='4')
		{
			while (!weatherfile.eof())
			{
			if (rainfall > 0)
			{ 

			}
			}
			
		}
		else if (selection=='5')
		{
			while (!weatherfile.eof())
			{
				
			}
		}
		else if (selection=='6')
		{
			cout << "Goodbye. Thank you for using my program.\n\n";
			done = true;					// flag for exit
		}
		else
		{
			cout << "** Invalid Selection. **\n\n";
		}
		weatherfile.close();

	} // end of while loop

	return (0);
}

OK then, I'll give you the simpler suggestion. (Don't worry, I won't do your work for you.) It doesn't have the same coolness factor, but it is just as effective.

Since you have several options that require you to parse the file once for each option, that means you will have to repeat a lot of code to do basically the same thing in your already very large, hard to read (because it is so big) main() function.

What I suggest that you do is make another function that handles all the parsing of the file. All you have to do is tell it which field number you are interested in, and the function will search through the file and compute the minimum, maximum, and average for the selected field.

You may also want to control which subset of records are accessed based upon the date. For example, above in my example I only accessed records where field 0 contained the date "07/01/1999".

So, given those options (pronounced arg-u-ments ;) ) we can write a function prototype:

void read_file(
  ifstream& file,        // The open and ready-to-read csv data file
  string    targetdate,  // The date we are interested in (see note below)
  int       fieldindex,  // The index of the field we are interested in
  double&   min,         // Where to put the minimum of the indexed field
  double&   max,         // Where to put the maximum
  double&   avg          // Where to put the average
  );

You can then, inside the function, gather all the required information (min,max,avg) and return them via the reference arguments. You'll have to fill in the body of the function. (Don't forget to reset the file at the end of the function.)

Now, to find the daily min/max temp for a specific day, you can just say:

string targetdate = "01/07/1999"; // whatever the target day is
double min_temp, max_temp, avg_temp;
read_file( weatherfile, targetdate, min_temp, max_temp, avg_temp );
cout << targetdate << ": ";
cout << setw(10) << setprecision(2) << min_temp;
cout << setw(10) << setprecision(2) << max_temp;

note
This seems a fairly intense project. Is the data file you posted the entire datafile, or are other days involved (like "01/08/1999")?

If it is just one day you can forget all that stuff about the target date.

But if it is more than one day then you'll have to either loop on the date or ask the user which date he is interested in.


The point
The whole reason I suggest this is to break things up into smaller, individual things. When you can concentrate on doing one thing (or less than three things) right at a time, and not have to worry about anything else, then it is much easier to see how your program works and fits together.

The main() function should direct the show, but avoid doing all the dirty work. Make sense?

Hope this helps.

This is the entire datafile I'm using, it encompasses 3 days of data.

This is the entire datafile I'm using, it encompasses 3 days of data.

Joy. So, when the user presses '2' is the program supposed to ask for the day or just list the min & max temp for each day in the file?

[edit] and if I'm quick enough on this edit, does your teacher expect you to split the date up into numbers or can you just assume that the user will input a complete and properly constructed date?

Just for the minimum and maximum temperature for each day in the file.

More joy.

You are going to have to get the dates you can use out of the file too.

Before I suggest much further, I think you ought to go talk to your teacher for specific help on the assignment. I don't want to get you doing too much stuff he may not be looking for.

Mmmm. Dinner was good.

Thanks for the link. It looks like I've got you going the right way.

What I suggest doing also is making another function that just scans the file for unique dates and puts them in some sort of iterative container (like an array or a vector).

If you are allowed to use vectors, you can just return a vector of dates: vector<string> get_dates( ifstream& file ); If you aren't, you could use new to allocate an array for the dates and return it: string* get_dates( ifstream& file ); You would have to delete[] the returned array before your program terminates.

Or you could just pass in a reference to an array: void get_dates( ifstream& file, string dates[], int& size ); (where size tells on input how large the array is and on output tells how many elements were actually used).

Or something like that. The function would work very much like the other function I suggested, except all you have to do is extract each line, from the file, and from each line extract the first field, and add it to the array if it isn't already there.

Then, when you are asked about, say, min/max temp, ... for every day, just run a loop that calls the other function I suggested with each date and print out the date and results before continuing with the next loop.


If you think that it would make things look cleaner, you could also write functions specifically for each case of your switch statement.

Anyway, I hope this helps. Work with it a bit and see what you can figure out. Post back if you have any problems or anything.

Yeah I have a problem when I ever try to compile the program it comes out with these errors. "setw" identifier not found, "set precision" identifier not found and "readfile function doesn't take 5 arguments."

///
///
///
///
///
/// Program: Weather data processing
/// Created by: Wesley Montgomery
/// This program anlizes weather data accessed from a file and finds the average of Temperature, Humidity, and other facts.
///
///
///

#include <fstream>	
#include <iostream>
#include <string>
#include <cmath>
#include <stdlib.h>
#include <algorithm>  // for min() and max()
#include <sstream>


using namespace std;

void read_file(
  ifstream& file,        // The open and ready-to-read csv data file
  string    targetdate,  // The date we are interested in (see note below)
  int       fieldindex,  // The index of the field we are interested in
  double&   min,         // Where to put the minimum of the indexed field
  double&   max,         // Where to put the maximum
  double&   avg          // Where to put the average
  );
void get_dates( ifstream& file, string dates[], int& size );

int main()
{ 
	int pressure, temp, windspeed, humidity, rainfall, peakwindspeed, min_temp, max_temp, totalrainfall;
	bool  done; // exit flag 
	char  selection; //Menu Selection
	string file; // Name of datafile
	ifstream weatherfile; //datafile stream


	// Initialize exit flag
	 done = false;

	while (!done) 
	{
		// Output menu list
		cout << "\n\n";
		cout << "************************\n\n";		
		cout << "  Weather Data Analysis: \n";		
		cout << "  1) Select Data File to be loaded\n";		
		cout << "  2) Daily Min/max of Temp,Pressure and humidity\n";		
		cout << "  3) Daily Max Wind Speed\n";		
		cout << "  4) Avg Pressure, Humidity, and Windspeed for rainy days\n";	
		cout << "  5) \n";
		cout << "  6) Exit Program\n";
		cout << "************************\n\n";		

		// Input data					
		cout << "Selection -> ";		
		cin >> selection;
		cout << "\n\n";

		// Process input
		if (selection=='1') 
		{
			cout << "Insert Data file:";
			cin >> file; 
			weatherfile.open (file.c_str(), ios::in);
			cout << "\n\n";
		}
		else if (selection=='2')
		{
			while (!weatherfile.eof())
			{
				string targetdate = "01/07/1999"; // whatever the target day is
               double min_temp, max_temp, avg_temp;
              read_file( weatherfile, targetdate, min_temp, max_temp, avg_temp );
              cout << targetdate << ": ";
              cout << setw(10) << setprecision(2) << min_temp;
              cout << setw(10) << setprecision(2) << max_temp;
			}
			weatherfile.clear();
            weatherfile.seekg( 0 );
		}
		
		else if (selection=='3')
		{
			while (!weatherfile.eof())
			{
			}
			weatherfile.clear();
            weatherfile.seekg( 0 );
		}
		else if (selection=='4')
		{
			while (!weatherfile.eof())
			{
			if (rainfall > 0)
			{ 

			}
			}
			weatherfile.clear();
            weatherfile.seekg( 0 );
		}
		else if (selection=='5')
		{
			while (!weatherfile.eof())
			{

				
			}
			weatherfile.clear();
            weatherfile.seekg( 0 );
		}
		else if (selection=='6')
		{
			cout << "Goodbye. Thank you for using my program.\n\n";
			done = true;					// flag for exit
		}
		else
		{
			cout << "** Invalid Selection. **\n\n";
		}
		weatherfile.close();

	} // end of while loop

	return (0);
}

Is there any problem with my code?

You forgot to list the index of the field you want to max/min/avg.

To use setw() and the like you must #include <iomanip> Hope this helps.

the "read file doesn't take # arguments" is still appearing.

the "read file doesn't take # arguments" is still appearing.

Function declaration:

void read_file(
  ifstream& file,        // The open and ready-to-read csv data file
  string    targetdate,  // The date we are interested in (see note below)
  int       fieldindex,  // The index of the field we are interested in
  double&   min,         // Where to put the minimum of the indexed field
  double&   max,         // Where to put the maximum
  double&   avg          // Where to put the average
  );

Function call:

read_file( weatherfile, targetdate, min_temp, max_temp, avg_temp );

The first has six arguments. The second only has five. Your function calls need to match your function declarations both in number of parameters within the parentheses and parameter types. This one does not.

Ok I tried to make seperate functions for each of the things but this error comes up: error C2664: 'read_file' : cannot convert parameter 4 from 'overloaded-function' to 'double &'

///
///
///
///
///
/// Program: Weather data processing
/// Created by: Wesley Montgomery
/// This program anlizes weather data accessed from a file and finds the average of Temperature, Humidity, and other facts.
///
///
///

#include <fstream>	
#include <iostream>
#include <string>
#include <cmath>
#include <stdlib.h>
#include <algorithm>  // for min() and max()
#include <sstream>
#include <iomanip>


using namespace std;

void read_file(
  ifstream& file,        // The open and ready-to-read csv data file
  string    targetdate,  // The date we are interested in (see note below)
  int       temp, // The index of the field we are interested in
  double&   min,         // Where to put the minimum of the indexed field
  double&   max        // Where to put the maximum
);

void read_filepres(
  ifstream& file,        // The open and ready-to-read csv data file
  string    targetdate,  // The date we are interested in (see note below)
  int       pressure, // The index of the field we are interested in
  double&   min,         // Where to put the minimum of the indexed field
  double&   max        // Where to put the maximum
);

void read_filehum(
  ifstream& file,        // The open and ready-to-read csv data file
  string    targetdate,  // The date we are interested in (see note below)
  int       humidity, // The index of the field we are interested in
  double&   min,         // Where to put the minimum of the indexed field
  double&   max        // Where to put the maximum
);

void read_filewindmax(
  ifstream& file,        // The open and ready-to-read csv data file
  string    targetdate,  // The date we are interested in (see note below)
  int       wind, // The index of the field we are interested in
  double&   max        // Where to put the maximum
);

void get_dates( ifstream& file, string dates[], int& size );

int main()
{ 
	int pressure, temp, windspeed, humidity, rainfall, min_temp, max_temp, min_pres, max_pres, min_humi, max_humi, wind_max;
	bool  done; // exit flag 
	char  selection; //Menu Selection
	string file; // Name of datafile
	ifstream weatherfile; //datafile stream


	// Initialize exit flag
	 done = false;

	while (!done) 
	{
		// Output menu list
		cout << "\n\n";
		cout << "************************\n\n";		
		cout << "  Weather Data Analysis: \n";		
		cout << "  1) Select Data File to be loaded\n";		
		cout << "  2) Daily Min/max of Temp,Pressure and humidity\n";		
		cout << "  3) Daily Max Wind Speed\n";		
		cout << "  4) Avg Pressure, Humidity, and Windspeed for rainy days\n";	
		cout << "  5) \n";
		cout << "  6) Exit Program\n";
		cout << "************************\n\n";		

		// Input data					
		cout << "Selection -> ";		
		cin >> selection;
		cout << "\n\n";

		// Process input
		if (selection=='1') 
		{
			cout << "Insert Data file:";
			cin >> file; 
			weatherfile.open (file.c_str(), ios::in);
			cout << "\n\n";
		}
		else if (selection=='2')
		{
			while (!weatherfile.eof())
			{
				string targetdate = "04/18/2008"; // whatever the target day is
               double min_temp, max_temp, min_pres, max_pres, min_humi, max_humi;
              read_file( weatherfile, targetdate, temp, min, max);
              cout << targetdate << ": ";
              cout << "The Minimum Temperature is" << setw(10) << setprecision(2) << min_temp << "degrees." << endl;
              cout << "The Maximum Temperature is" << setw(10) << setprecision(2) << max_temp << "degrees." << endl;
			  read_filepres( weatherfile, targetdate, pressure, min, max);
			  cout << "The Minimum Pressure is" << setw(10) << setprecision(2) << min_pres << "millibars." << endl;
              cout << "The Maximum Pressure is" << setw(10) << setprecision(2) << max_pres << "millibars." << endl;
			  read_filehum( weatherfile, targetdate, humidity, min, max);
			  cout << "The Minimum Humidity is" << setw(10) << setprecision(2) << min_humi << endl;
              cout << "The Maximum Humidity is" << setw(10) << setprecision(2) << max_humi << endl;
			}
			weatherfile.clear();
            weatherfile.seekg( 0 );
		}
		
		else if (selection=='3')
		{
			while (!weatherfile.eof())
			{
				string targetdate = "04/18/2008"; // whatever the target day is
               double peakwindspeed;
              read_filewindmax(weatherfile, targetdate, windspeed, max);
              cout << targetdate << ": ";
              cout << "The Maximum Wind Speed is" << setw(10) << setprecision(2) << wind_max << "miles per hour." << endl;
			}
			weatherfile.clear();
            weatherfile.seekg( 0 );
		}
		else if (selection=='4')
		{
			while (!weatherfile.eof())
			{
			if (rainfall > 0)
			{ 

			}
			}
			weatherfile.clear();
            weatherfile.seekg( 0 );
		}
		else if (selection=='5')
		{
			while (!weatherfile.eof())
			{

				
			}
			weatherfile.clear();
            weatherfile.seekg( 0 );
		}
		else if (selection=='6')
		{
			cout << "Goodbye. Thank you for using my program.\n\n";
			done = true;					// flag for exit
		}
		else
		{
			cout << "** Invalid Selection. **\n\n";
		}
		weatherfile.close();

	} // end of while loop

	return (0);
}

Any help on this?

Ok I tried to make seperate functions for each of the things but this error comes up: error C2664: 'read_file' : cannot convert parameter 4 from 'overloaded-function' to 'double &'


Any help on this?

read_file( weatherfile, targetdate, temp, min, max);

min and max are never declared. They are declared in your function declaration, but that doesn't help you outside of the function itself. I see this line directly above the line I just listed:

double min_temp, max_temp, min_pres, max_pres, min_humi, max_humi;

Did you mean to put min_temp and max_temp rather than min and max?

read_file( weatherfile, targetdate, temp, min_temp, max_temp);

Also, do these functions exist? I don't see them in the code you posted. If they don't exist, you'll get a linker error.

Finally, it's fine to use the same function name with different parameter lists. You don't have to name them all something different. It's called "function overloading". Type that into a search engine and you'll get lots of hits. Here's one:

http://www.codersource.net/cpp_tutorial_function_overloading.html

C++ figures out which function you are calling by the parameters you use. My point in the last post was that for every function call you make, you must have one and exactly one function with that name that takes that number of parameters and those types of parameters. At the time of that post, you did not, so you got an error. You now have the function declarations, but not the functions themselves, it appears, so you will still get an error, though this time it will be a linker error unless there is some code with those functions that I missed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.