| | |
A wee bit of help
![]() |
Argh.
OK. You are parsing a standard CSV file, with a header record.
Handle it thus:
Hope this helps.
OK. You are parsing a standard CSV file, with a header record.
Handle it thus:
C++ Syntax (Toggle Plain Text)
#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.
Last edited by Duoas; May 26th, 2008 at 1:23 pm. Reason: fixed bloomin typo
•
•
Join Date: May 2008
Posts: 23
Reputation:
Solved Threads: 0
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
Now is there any problems with this skeketon of a code that makes what you suggested not work?
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
C++ Syntax (Toggle Plain Text)
/// /// /// /// /// /// 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); }
Last edited by WesFox13; May 26th, 2008 at 2:25 pm.
•
•
Join Date: Jan 2008
Posts: 3,950
Reputation:
Solved Threads: 515
•
•
•
•
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?
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. Last edited by VernonDozier; May 26th, 2008 at 2:57 pm.
Oops! I switch between C++ and Delphi a lot... so those
)
You will also have to do the following after each time you look through the entire file:
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.)
:=s should be =s... (sorry
)You will also have to do the following after each time you look through the entire file:
C++ Syntax (Toggle Plain Text)
weatherfile.clear(); weatherfile.seekg( 0 );
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.)
Last edited by Duoas; May 26th, 2008 at 3:05 pm.
•
•
Join Date: May 2008
Posts: 23
Reputation:
Solved Threads: 0
Btw here's what I have so far in my code
C++ Syntax (Toggle Plain Text)
/// /// /// /// /// /// 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:
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:
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.
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: C++ Syntax (Toggle Plain Text)
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 );
Now, to find the daily min/max temp for a specific day, you can just say:
C++ Syntax (Toggle Plain Text)
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.
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?
[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?
Last edited by Duoas; May 26th, 2008 at 7:43 pm.
![]() |
Similar Threads
- HELP!! Monitor is showing RED color in place of WHITE (Monitors, Displays and Video Cards)
- game in c pragraming (IT Professionals' Lounge)
- Book Review - SEO Book by Aaron Wall (Promotion and Marketing Plans)
- invitation for Yahoo IM id's (Geeks' Lounge)
- A problem with a given Syntax! (Computer Science)
- 3500+ vs 3.4ghz (Motherboards, CPUs and RAM)
- New to Linux (Getting Started and Choosing a Distro)
- IE is hijacked by http://th.msie.cc/index.php?aid=20035 (Viruses, Spyware and other Nasties)
- window loses focus on CR (Web Browsers)
Other Threads in the C++ Forum
- Previous Thread: i want to know what the following function is doing?
- Next Thread: Structure members resetting
Views: 2342 | Replies: 38
| Thread Tools | Search this Thread |
Tag cloud for C++
6 algorithm array arrays assignment basic beginner binary c++ c/c++ calculator char class classes client code command compile compiler constructor conversion convert count data delete dll dynamic encryption error file files fstream function functions game givemetehcodez graph gui helpwithhomework homework iamthwee input int lazy link linker list loop loops math matrix memory newbie number numbers object objects opengl operator output parameter pointer pointers problem program programming project python random read recursion recursive reference search server sockets sort spoonfeeding string strings struct student studio template templates text time tree undefined variable vc++ vector video visual void win32 window windows winsock wordfrequency






