can't figue out what is wrong with the programme

This is a discussion on can't figue out what is wrong with the programme within the C++ Programming forums, part of the General Programming Boards category; I see a couple of issues with your reader code -- in ReadFromFile() function: - you are breaking out of ...

  1. #16
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    I see a couple of issues with your reader code -- in ReadFromFile() function:

    - you are breaking out of the loop before storing the last record in the list.
    - you seem not to be skipping newlines at the end of the lines.

    I'm surprised it's working at all without the newline skipping. Maybe a platform difference.

    By my second point I mean:

    Code:
        // final iteration through loop
    
            getline(InFile, Designation);  //read last record
            getline(InFile, Agent);
            InFile >> Temperature;
            InFile >> Count;
            InFile >> Index;
            
            InFile.ignore(100, '\n');  // now at EOF
            
            if(InFile.eof())
                break;
        
            // remaining statements are unreachable    
            // so last record is not stored in List
            Temp.SetDesignation( Designation );
    Just move the break down a bit.

    The other problem is with the iterator ILister. Here:
    Code:
            cout << "\nLowest Temperature:\t " << GetMinF() //Second problem
            << "\t\t\t" << (*ILister).Convert( GetMinF() );
    You are relying on ILister always pointing to a valid list entry when you deference it to call Convert(). This is not true here -- within GetMinF and GetMaxF you use ILister in the for loop, so when you get to here ILister is pointing past the end of the list!

    Basically every time you use ILister you need to initialise it first -- because you have lots of for loops that can modify the value, you can't rely on it persisting or having a sensible value. For calls like the above call to Convert() you don't seem to need a particular element -- so you could just use List.begin() I think.

    Shout if any of that is unclear.

  2. #17
    Registered User
    Join Date
    Mar 2011
    Posts
    9
    Quote Originally Posted by jimblumberg View Post
    I changed the code for GetMinF() to this and the min temperature works ok.
    Code:
    double VectorList::GetMinF()
    {
    	double minF;
    
    	//minF = ILister->GetTemperature();
    	minF = 1000.0;
    I think the problem with your temperature conversion routine is that you are doing integer math.
    Code:
    double WeatherStation::Convert(double degreeF)
    {
    	double degreeC;
    
    	// convert Fahrenheit to Celcius
    	//degreeC = ((degreeF - 32) * 5) / 9; /// This is integer math
            degreeC = ((degreeF - 32.0) * 5.0) / 9.0;  // Should Be this
    	return degreeC;
    }
    Jim
    [indent]
    Jim, you are a life-saver. Thank you very very much. With your help, now my programme runs without any flaws.

  3. #18
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,768
    Again, indent your code. If there is something you don't understand, ask. No one wants to look at unindented code. It's the VERY FIRST thing ANY programmer must do with his/her code.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #19
    Registered User
    Join Date
    Mar 2011
    Posts
    9
    Quote Originally Posted by Elysia View Post
    Again, indent your code. If there is something you don't understand, ask. No one wants to look at unindented code. It's the VERY FIRST thing ANY programmer must do with his/her code.

    Elysia, I am kind of a beginner in programming. So, I don't know too much about indentation. Anyway, somewhere in the internet I found that to indent the code I put my code between "indent and /indent". That's all I know about indentation. And, that's how I have been indenting my code in this forum. If that is not a right way to indent the code, could you please tell me how to indent the code properly? I would greatly appreciate your help.
    Last edited by philiplahm; 03-27-2011 at 02:09 AM.

  5. #20
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,768
    Indentation is this:
    Code:
    #include <iostream>
    #include <string> 
    #include <vector>
    #include <fstream>
    
    using namespace std;
    
    
    class PollenAirQuality
    {
    public:
    	PollenAirQuality() {PollenCount= AirIndex= 0; }
    	void SetPollenCount(double Count) { PollenCount = Count; }
    	double GetPollenCount() { return PollenCount;}
    	void SetAirIndex(double Index) { AirIndex = Index; }
    	double GetAirIndex() {return AirIndex; }
    
    protected:
    	double PollenCount;
    	double AirIndex;
    
    };
    
    
    
    class WeatherStation : public PollenAirQuality
    {
    public:
    	WeatherStation();
    
    	void SetDesignation(string ID) { StationDesignation = ID; }
    	void SetAgent(string Agent) { StationAgent = Agent; }
    	void SetTemperature(double Degree) { Temperature = Degree; }
    
    	double Convert(double DegreeF);
    
    	string GetDesignation() { return StationDesignation; }
    	string GetAgent() { return StationAgent; }
    	double GetTemperature() { return Temperature; }
    
    protected:
    	string StationDesignation;
    	string StationAgent; 
    	double Temperature; 
    
    };
    
    WeatherStation::WeatherStation()
    {
    	StationDesignation = "";
    	StationAgent = "";
    	Temperature = 0;
    }
    
    double WeatherStation::Convert(double degreeF)
    {
    	double degreeC;
    
    	// convert Fahrenheit to Celcius
    	degreeC = ((degreeF - 32) * 5) / 9;
    
    	return degreeC;
    }
    
    class VectorList
    {
    	vector<WeatherStation> List;
    	vector<WeatherStation>::iterator ILister;
    
    	string FileName;
    
    public:
    	VectorList() { FileName = "Temp"; }
    	VectorList(string FName) { FileName = FName; }
    
    	void AddStations();
    	void PostStationInfo();
    	void DailyReport();
    	void HighLowReport();
    	void PollenCount();
    	void AirQualityIndex();
    	double GetMaxF();
    	double GetMinF();
    	double GetAvgF();
    
    	void SetFileName(string FName) { FileName = FName; }
    	void WriteToFile();
    	void ReadFromFile();
    
    };
    
    void VectorList::AddStations()
    {
    	WeatherStation Station;
    	string Designation, Agent;
    
    	cout << "Enter Station Information Below, Stop To Quit\n";
    
    	for (;;)
    	{
    		cout << "\n-------------------------------\n";
    
    		cout << "Enter Weather Station Designation: ";
    		getline (cin, Designation);
    		if (Designation == "Stop")
    			break;
    		Station.SetDesignation( Designation );
    
    		cout << "\nEnter Contact Person: ";
    		getline (cin, Agent);
    		if (Agent == "Stop")
    			break;
    		Station.SetAgent( Agent );
    
    		cout << "\n-------------------------------\n";
    
    		List.push_back(Station);
    
    	}
    }
    void VectorList::PostStationInfo()
    { 
    	double Degree, Count, Index;
    
    	cout << "Enter reported temperatures: (in Fahrenheit) \n\n";
    
    	for (ILister = List.begin(); ILister < List.end(); ILister++)
    	{
    		cout << ILister->GetDesignation() << ":\n";
    		cout << ILister->GetAgent();
    
    		cout << "\nEnter Temperature:\t";
    		cin >> Degree;
    		ILister->SetTemperature( Degree );
    
    		cout << "\n\tPollen Count:\t";
    		cin >> Count;
    		ILister->SetPollenCount( Count );
    
    		cout << "\n\tAir Quality Index:\t";
    		cin >> Index;
    		ILister->SetAirIndex( Index );
    
    		cin.ignore(100, '\n');
    	}
    }
    
    void VectorList::DailyReport()
    {
    	cout << " NGS Daily Temperature Report \n";
    	cout << "===========================================================\n";
    	cout << "\t\t Fahrenheit(F) \t Celsius (C)";
    
    	for (ILister = List.begin(); ILister < List.end(); ILister++)
    	{
    		cout << "\n-----------------------------------------------------------\n";
    		cout << (*ILister).GetDesignation() << "\t\t ";
    		cout << (*ILister).GetTemperature() << "\t\t\t" 
    			<< (*ILister).Convert( (*ILister).GetTemperature() );
    	}
    
    	cout << "\n-----------------------------------------------------------";
    	cout << "\nMean Temperature: \t " << GetAvgF() // The first problem is here
    		<< "\t\t\t" << (*ILister).Convert(GetAvgF() );
    	cout << "\n===========================================================\n\n";
    }
    
    void VectorList::HighLowReport()
    {
    	cout << " NGS High-Low Report ";
    	cout << "\n==========================================================";
    	cout << "\n\t\t Fahrenheit(F) \t Celsius (C)";
    	cout << "\n----------------------------------------------------------";
    	cout << "\nLowest Temperature:\t " << GetMinF() //Second problem
    		<< "\t\t\t" << (*ILister).Convert( GetMinF() );
    	cout << "\n----------------------------------------------------------";
    	cout << "\nHighest Temperature:\t " << GetMaxF() //Third problem
    		<< "\t\t\t" << (*ILister).Convert( GetMaxF() );
    	cout << "\n----------------------------------------------------------";
    	cout << "\n==========================================================\n";
    }
    
    
    void VectorList::PollenCount()
    {
    
    	cout << " NGS Daily Pollen Report\n";
    	cout << "==================================\n";
    
    	for (ILister = List.begin(); ILister < List.end(); ILister++)
    	{
    		cout << ILister->GetDesignation() << ":\t\t" << ILister->GetPollenCount() << "\n";
    	}
    	cout << "==================================\n\n";
    }
    
    void VectorList:: AirQualityIndex()
    {
    	cout << " NGS Air Quality Index  Report\n";
    	cout << "==================================\n";
    
    	for (ILister = List.begin(); ILister < List.end(); ILister++)
    	{
    		cout << ILister->GetDesignation() << ":\t\t" << ILister->GetAirIndex() << "\n";
    	}
    	cout << "==================================\n\n";
    }
    
    double VectorList::GetMaxF()
    {
    	double maxF;
    
    	maxF = ILister->GetTemperature();
    
    	for (ILister = List.begin(); ILister < List.end(); ILister++)
    	{
    		// find the highest temperture in Fahrenheit
    		if ( (*ILister).GetTemperature() > maxF)
    			maxF = (*ILister).GetTemperature();
    	}
    	return maxF;
    }
    double VectorList::GetMinF()
    {
    	double minF;
    
    	minF = ILister->GetTemperature();
    	for (ILister = List.begin(); ILister < List.end(); ILister++)
    	{
    		// find the lowest temperture in Fahrenheit
    		if ( (*ILister).GetTemperature() < minF)
    			minF = (*ILister).GetTemperature();
    	}
    	return minF;
    }
    
    
    double VectorList::GetAvgF()
    {
    	double Total = 0, Mean;
    
    	for (ILister = List.begin(); ILister < List.end(); ILister++)
    		Total += ILister->GetTemperature();
    
    	Mean = Total / List.size();
    
    	return Mean;
    }
    void VectorList::WriteToFile() 
    {
    	fstream OutFile(FileName.c_str(), ios::out);
    
    	for ( ILister = List.begin(); ILister < List.end(); ILister++)
    	{
    		OutFile << ILister->GetDesignation() << endl;
    		OutFile << ILister->GetAgent() << endl;
    		OutFile << ILister->GetTemperature() << endl;
    		OutFile << ILister->GetPollenCount() << endl;
    		OutFile << ILister->GetAirIndex() << endl;
    	}
    
    	OutFile.close();
    }
    
    void VectorList::ReadFromFile()
    {
    	fstream InFile(FileName.c_str(), ios::in);
    
    	string Designation, Agent;
    	double Temperature, Count, Index;
    	WeatherStation Temp;
    
    	while(true)
    	{
    		getline(InFile, Designation); 
    		getline(InFile, Agent);
    		InFile >> Temperature;
    		InFile >> Count;
    		InFile >> Index;
    
    		InFile.ignore(100, '\n'); 
    
    		if(InFile.eof())
    			break;
    
    		Temp.SetDesignation( Designation );
    		Temp.SetAgent( Agent );
    		Temp.SetTemperature( Temperature );
    		Temp.SetPollenCount( Count );
    		Temp.SetAirIndex( Index );
    
    		List.push_back(Temp);
    	}
    	InFile.close();
    }
    
    void Menu();
    int main()
    {
    	int I = 0; 
    
    	VectorList Station;
    	string Command;
    
    	while(true)
    	{
    		Menu();
    		cout << "Enter Command: ";
    		getline (cin, Command);
    		cout << "\n\n";
    
    		if (Command == "Add Stations")
    		{
    			Station.AddStations();
    			I = 1;
    		}
    		if (Command == "Post Station Info" && I == 1)
    		{ 
    			Station.PostStationInfo();
    			I = 2; 
    		}
    		if (Command == "Quit")
    			break;
    		else 
    		{
    			if ( I == 1 )
    				cout << "\nPlease Post Station Info\n";
    			if (Command == "Daily Report" && I == 2)
    				Station.DailyReport();
    			if (Command == "High-Low Report" && I == 2)
    				Station.HighLowReport();
    			if (Command == "Daily Pollen Count" && I == 2)
    				Station.PollenCount();
    			if (Command == "Daily Air Quality Index" && I == 2)
    				Station.AirQualityIndex();
    			if (Command == "Change File Name")
    			{
    				string FName;
    				cout << "Enter File Name: ";
    				getline(cin, FName);
    				Station.SetFileName(FName);
    				cout << "File Name is Changed";
    			}
    			if (Command == "Save To File")
    			{ 
    				Station.WriteToFile();
    				cout << "File is saved\n";
    			}
    			if (Command == "Read From File")
    			{
    				Station.ReadFromFile();
    				I = 2;
    				cout << "Opened Saved File\n";
    			}
    		}
    	}
    }
    
    void Menu()
    {
    	cout << "\nChoices:";
    	cout << "\n---------------------------";
    	cout << "\n Add Stations";
    	cout << "\n Post Station Info";
    	cout << "\n Daily Report";
    	cout << "\n High-Low Report";
    	cout << "\n Daily Pollen Count";
    	cout << "\n Daily Air Quality Index";
    	cout << "\n Change File Name";
    	cout << "\n Save To File";
    	cout << "\n Read From File";
    	cout << "\n Quit";
    	cout << "\n---------------------------\n";
    }
    Which you should have understood from the article posted earlier.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #21
    Registered User
    Join Date
    Mar 2011
    Posts
    9
    Quote Originally Posted by smokeyangel View Post
    I see a couple of issues with your reader code -- in ReadFromFile() function:

    - you are breaking out of the loop before storing the last record in the list.
    - you seem not to be skipping newlines at the end of the lines.

    I'm surprised it's working at all without the newline skipping. Maybe a platform difference.

    By my second point I mean:

    Code:
        // final iteration through loop
    
            getline(InFile, Designation);  //read last record
            getline(InFile, Agent);
            InFile >> Temperature;
            InFile >> Count;
            InFile >> Index;
            
            InFile.ignore(100, '\n');  // now at EOF
            
            if(InFile.eof())
                break;
        
            // remaining statements are unreachable    
            // so last record is not stored in List
            Temp.SetDesignation( Designation );
    Just move the break down a bit.

    The other problem is with the iterator ILister. Here:
    Code:
            cout << "\nLowest Temperature:\t " << GetMinF() //Second problem
            << "\t\t\t" << (*ILister).Convert( GetMinF() );
    You are relying on ILister always pointing to a valid list entry when you deference it to call Convert(). This is not true here -- within GetMinF and GetMaxF you use ILister in the for loop, so when you get to here ILister is pointing past the end of the list!

    Basically every time you use ILister you need to initialise it first -- because you have lots of for loops that can modify the value, you can't rely on it persisting or having a sensible value. For calls like the above call to Convert() you don't seem to need a particular element -- so you could just use List.begin() I think.

    Shout if any of that is unclear.

    You were right about the "ILister". I should not be depending on it because it has been used in many for loops. Anyway, I fixed that problem. But, about the ReadFromFile, I am not really sure how it is not storing the last record of the list. Because I am using a "break", right after the user enter the Air Index value, it seems to me that it is recording everything it is supposed to record.


    Thank you for your response, Elysia. The code with indentation, indeed, looks really clear and attractive. But, I am not really sure which article you were referring to when you said "I should have understood from the article posted earlier".
    But, anyway is there any chance that you could tell me how you indented the code above? I would love to learn it.
    Last edited by philiplahm; 03-27-2011 at 02:29 AM.

  7. #22
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,768
    Look at the post
    http://cboard.cprogramming.com/cplus...ml#post1014830

    For the how, look closely where new tabs are introduces. There is a pattern.
    The link in the reply is also a good source for understand it.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #23
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    Quote Originally Posted by philiplahm View Post

    You were right about the "ILister". I should not be depending on it because it has been used in many for loops. Anyway, I fixed that problem. But, about the ReadFromFile, I am not really sure how it is not storing the last record of the list. Because I am using a "break", right after the user enter the Air Index value, it seems to me that it is recording everything it is supposed to record.
    Good, glad you fixed the ILister problem.

    About your second point:

    Code:
    void VectorList::ReadFromFile()
    {
    	fstream InFile(FileName.c_str(), ios::in);
    
    	string Designation, Agent;
    	double Temperature, Count, Index;
    	WeatherStation Temp;
    
    	while(true)
    	{
    		getline(InFile, Designation); 
    		getline(InFile, Agent);
    		InFile >> Temperature;
    		InFile >> Count;
    		InFile >> Index;
    
    		InFile.ignore(100, '\n'); 
    
    		if(InFile.eof())
    			break;
    
    		Temp.SetDesignation( Designation );
    		Temp.SetAgent( Agent );
    		Temp.SetTemperature( Temperature );
    		Temp.SetPollenCount( Count );
    		Temp.SetAirIndex( Index );
                    /****  There are 4 records in the file but this statement is only
                                executed 3 times -- only 3 items are pushed to the list ***/
    		List.push_back(Temp);
    	}
           /* Execution resumes here after break. */
    	InFile.close();
    }
    So, on the last iteration through the loop, the program will read in the information from the file into the local variables Designation, Agent, Temperature, Count, Index. So, it is read out of the file.

    The problem is that the break is before the code has initialised Temp and push_back()ed it onto the list.

    That said, you said that it 'worked flawlessly' with a change that shouldn't have made any difference to this. So maybe our systems are behaving differently to each other. To be clear I compiled it and ran it --
    With the break in the initial position::
    NGS High-Low Report
    ================================================== ========
    Fahrenheit(░F) Celsius (░C)
    ----------------------------------------------------------
    Lowest Temperature: 53 11.6667
    ----------------------------------------------------------
    Highest Temperature: 61 16.1111
    ----------------------------------------------------------
    ================================================== ========


    With the break at the end of the while loop:
    NGS High-Low Report
    ================================================== ========
    Fahrenheit(░F) Celsius (░C)
    ----------------------------------------------------------
    Lowest Temperature: 48 8.88889
    ----------------------------------------------------------
    Highest Temperature: 61 16.1111
    ----------------------------------------------------------
    ================================================== ========

  9. #24
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,651
    Look into using an editor or IDE that actually does the indentation for you. What are you using to write your programs?

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 05-13-2007, 08:55 AM
  2. Programme Efficiency
    By Cikotic in forum C Programming
    Replies: 3
    Last Post: 06-28-2004, 01:29 PM
  3. Gui Programme does'nt Compiles from DOS
    By Shadowhunt in forum C++ Programming
    Replies: 1
    Last Post: 06-06-2003, 08:05 AM
  4. Simple C++ GUI programme does'nt run from dos
    By Shadowhunt in forum C++ Programming
    Replies: 4
    Last Post: 05-31-2003, 05:30 AM
  5. God
    By datainjector in forum A Brief History of Cprogramming.com
    Replies: 746
    Last Post: 12-22-2002, 11:01 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21