How To Encapsulate Functions In Code?

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

41 Replies - 1096 Views - Last Post: 07 November 2017 - 11:28 AM Rate Topic: -----

#1 11ash1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 25-October 15

How To Encapsulate Functions In Code?

Posted 03 November 2017 - 06:34 AM

Hello, I am told that I am needed to:
Project 7

Change the program to use structs for temperature, wind, and weather measurement.

Refactor your program so that the code for

- temperature is in two files (.h declarations) and (.cpp implementations)

- wind is in two files (.h declarations) and (.cpp implementations)

-WeatherMeasurement is in two files (.h declarations) and (.cpp implementations)

- And your main is in one file

I am not sure what it wants me to do. I needed to change my last program using structs which I did, but I have no idea how to do this. If someone could help I will really appreciate it.

here is my code using structs:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

struct temperature {
string name;
int choice;
int numOfReadings = 0;
int size;
double temperatures[4], windSpeeds[4];
string windDirection[4];
bool initialized = false;
} temp1, temp2,temp3,temp4;
//void moveTemperaturesToRight(temperature temperatures[], temperature windSpeeds[], temperature windDirection[]);
int main()
{
char str;
cout << "Enter the name of weather station: ";
getline(cin, temp2.name);
while (true)
{
cout << "I. Input a complete weather reading." << "\n";
cout << "P. Print the current weather." << "\n";
cout << "H. Print the weather history (from most recent to oldest)." << "\n";
cout << "E. Exit the program." << "\n";
cout << "Enter your choice: ";
cin >> str;
if (str != 'I'&& str != 'P'&& str != 'H'&& str != 'E')
temp4.choice = 0;
else
temp4.choice = str;
//Switch based on choice.
switch (temp4.choice)
{
case 'I':
//moveTemperaturesToRight(temperature temperatures[], temperature windSpeeds[], temperature windDirection[]);
cout << "Enter the temperature:";
cin >> temp1.temperatures[0];
do
{
cout << "Enter the wind speed (a value >=0):";
cin >> temp1.windSpeeds[0];
while (cin.fail() || (cin.peek() != '\r' && cin.peek() != '\n'))
{
cout << "Invalid Input! Re Enter the wind speed" << endl;
cin.clear();
while (cin.get() != '\n');
cin >> temp1.windSpeeds[0];
}
} while (temp1.windSpeeds[0] < 0);
//get correct wind direction
do
{
cout << "Enter the wind direction (North,South,East or West):";
cin >> temp2.windDirection[0];
} while (temp2.windDirection[0] != "North" && temp2.windDirection[0] != "South" && temp2.windDirection[0] != "East" && temp2.windDirection[0] != "West");
temp3.initialized = true;
if (temp3.initialized)
temp4.numOfReadings++;
if (temp4.numOfReadings > 4)
temp4.numOfReadings = 4;
break;
case 'H': //Print the current weather, if valid weather is entered.
cout << "Enter size of the history wants:";
cin >> temp4.size;
if (temp4.numOfReadings<temp4.size)
{
cout << "History size is high";
break;
}
for (int i = 0; i < temp4.size; i++)
{
cout << "*****" << temp1.name << "*****" << "\n";
cout << "Temperature: " << temp1.temperatures[i] << "\n";
cout << "Wind speed: " << temp1.windSpeeds[i] << "\n";
cout << "Wind direction: " << temp2.windDirection[i] << "\n" << "\n";
}
if (temp4.numOfReadings == 0)
cout << "Please enter the details before asking to print." << "\n";
break;
case 'P':
if (temp4.numOfReadings == 0)
{
cout << "Please enter the details before asking to print." << "\n";
break;
}
cout << "*****" << temp1.name << "*****" << "\n";
cout << "Temperature: " << temp1.temperatures[0] << "\n";
cout << "Wind speed: " << temp1.windSpeeds[0] << "\n";
cout << "Wind direction: " << temp2.windDirection[0] << "\n" << "\n";
break;
case 'E':
return 0; //Stops execution.
default:
cout << "Invalid choice. Please follow the menu." << "\n";
}
}
}



temperature.h

#pragma once

temperature.cpp

wind.h

#pragma once

wind.cpp

weatherMeasurement.h

#pragma once

weatherMeasurement.cpp

Is This A Good Question/Topic? 0
  • +

Replies To: How To Encapsulate Functions In Code?

#2 GazinAtCode  Icon User is offline

  • D.I.C Head

Reputation: 18
  • View blog
  • Posts: 70
  • Joined: 26-September 16

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 06:50 AM

The way your code looks now, I don't see how you could split it between the different .h and .cpp files. The concept you're talking about typically refers to the class definition being put in a header file and the member functions (methods) being defined in a corresponding source file. More info here: http://www.learncpp....d-header-files/

This post has been edited by GazinAtCode: 03 November 2017 - 06:53 AM

Was This Post Helpful? 0
  • +
  • -

#3 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2014
  • View blog
  • Posts: 5,397
  • Joined: 27-December 05

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 07:12 AM

It appears that you may not have followed the instructions for the previous assignment because the current assignment implies that the code for temperature, wind, and weather measurement are already separated (in the sense that they are contained in separate functions or classes). You have temperature and wind rolled together in your main function.

It's also not clear what "weather measurement" is meant to represent (as opposed to temperature and wind which I would think are both aspects of weather), but your code doesn't seem to deal with that at all.

I think it's really not possible to provide much useful advice without knowing exactly what the original assignment called for.
Was This Post Helpful? 0
  • +
  • -

#4 11ash1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 25-October 15

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 07:21 AM

Hello, what it wanted me to do in the first part of the assignment was to Change the program to use structs for temperature, wind, and weather measurement.

here is the code for project 6
#include "stdafx.h"

#include <iostream>

#include <string>

using namespace std;

void moveTemperaturesToRight(double temperatures[],

double windSpeed[],

string windDirection[])

{

for (int i = 3; i > 0; i--)

{

temperatures[i] = temperatures[i - 1];

windSpeed[i] = windSpeed[i - 1];

windDirection[i] = windDirection[i - 1];

}

}

int main()

{

string name;

int choice;

int numOfReadings = 0;

int size;

double temperatures[4], windSpeeds[4];

string windDirections[4];

bool initialized = false;

char str;

//Have the user provide a name for the weather station upon entry.

cout << "Enter the name of weather station: ";

getline(cin, name);

//Control loop to perform various actions.

while (true)

{

cout << "I. Input a complete weather reading." << "\n";

cout << "P. Print the current weather." << "\n";

cout << "H. Print the weather history (from most recent to oldest)." << "\n";

cout << "E. Exit the program." << "\n";

cout << "Enter your choice: ";

cin >> str;

if (str != 'I'&& str != 'P'&& str != 'H'&& str != 'E')

choice = 0;

else

choice = str;

//Switch based on choice.

switch (choice)

{

case 'I':

moveTemperaturesToRight(temperatures,

windSpeeds,

windDirections);

cout << "Enter the temperature:";

cin >> temperatures[0];

//get correct wind speed

do

{

cout << "Enter the wind speed (a value >=0):";

cin >> windSpeeds[0];

while (cin.fail() || (cin.peek() != '\r' && cin.peek() != '\n'))

{

cout << "Invalid Input! Re Enter the wind speed" << endl;

cin.clear();

while (cin.get() != '\n');

cin >> windSpeeds[0];

}

} while (windSpeeds[0] < 0);

//get correct wind direction

do

{

cout << "Enter the wind direction (North,South,East or West):";

cin >> windDirections[0];

} while (windDirections[0] != "North" && windDirections[0] != "South" && windDirections[0] != "East" && windDirections[0] != "West");

initialized = true;

if (initialized)

numOfReadings++;

if (numOfReadings > 4)

numOfReadings = 4;

break;

case 'H': //Print the current weather, if valid weather is entered.

cout << "Enter size of the history wants:";

cin >> size;

if (numOfReadings<size)

{

cout << "History size is high";

break;

}

for (int i = 0; i < size; i++)

{

cout << "*****" << name << "*****" << "\n";

cout << "Temperature: " << temperatures[i] << "\n";

cout << "Wind speed: " << windSpeeds[i] << "\n";

cout << "Wind direction: " << windDirections[i] << "\n" << "\n";

}

if (numOfReadings == 0)

cout << "Please enter the details before asking to print." << "\n";

break;

case 'P':

if (numOfReadings == 0)

{

cout << "Please enter the details before asking to print." << "\n";

break;

}

cout << "*****" << name << "*****" << "\n";

cout << "Temperature: " << temperatures[0] << "\n";

cout << "Wind speed: " << windSpeeds[0] << "\n";

cout << "Wind direction: " << windDirections[0] << "\n" << "\n";

break;

case 'E':

return 0; //Stops execution.

default:

cout << "Invalid choice. Please follow the menu." << "\n";

}

}

}

This post has been edited by Skydiver: 03 November 2017 - 09:08 AM
Reason for edit:: Removed unnecessary quote. No need to quote the post above yours.

Was This Post Helpful? 0
  • +
  • -

#5 jimblumberg  Icon User is offline

  • member icon

Reputation: 5336
  • View blog
  • Posts: 16,619
  • Joined: 25-December 09

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 07:37 AM

Quote

Change the program to use structs for temperature, wind, and weather measurement.

So what does the original program look like before you tried to add structs?

By the way I would expect your struct to look more like:

struct Temperature
{
    double temperatures;
    double windSpeeds;
    string windDirection;
};


Everything else would be variables local to the functions. And instead of having one struct that contains several arrays you would have an vector/array of struct like above.

Jim
Was This Post Helpful? 0
  • +
  • -

#6 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2014
  • View blog
  • Posts: 5,397
  • Joined: 27-December 05

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 07:43 AM

View Post11ash1, on 03 November 2017 - 10:21 AM, said:

Hello, what it wanted me to do in the first part of the assignment was to Change the program to use structs for temperature, wind, and weather measurement.


Yes, you said that already in post #1. But what was the ORIGINAL assignment? (Project 5, or 4 or whichever gives a clear picture of what you were supposed to do.)

And what is meant by "weather measurement" which your assignment seems to be distinguishing from temperature and wind.
Was This Post Helpful? 0
  • +
  • -

#7 11ash1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 25-October 15

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 07:51 AM

View Postjimblumberg, on 03 November 2017 - 07:37 AM, said:

Quote

Change the program to use structs for temperature, wind, and weather measurement.

So what does the original program look like before you tried to add structs?

By the way I would expect your struct to look more like:

struct Temperature
{
    double temperatures;
    double windSpeeds;
    string windDirection;
};


Everything else would be variables local to the functions. And instead of having one struct that contains several arrays you would have an vector/array of struct like above.

Jim


I added the program before structs in the comments
Was This Post Helpful? 0
  • +
  • -

#8 11ash1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 25-October 15

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 08:17 AM

View Postr.stiltskin, on 03 November 2017 - 07:43 AM, said:

View Post11ash1, on 03 November 2017 - 10:21 AM, said:

Hello, what it wanted me to do in the first part of the assignment was to Change the program to use structs for temperature, wind, and weather measurement.


Yes, you said that already in post #1. But what was the ORIGINAL assignment? (Project 5, or 4 or whichever gives a clear picture of what you were supposed to do.)

And what is meant by "weather measurement" which your assignment seems to be distinguishing from temperature and wind.


project 5
Extend the functionality of project 4 to

- incorporate a history of the past 4 weather measurements

- update the user menu to include

- printing the current weather

- printing the weather history (from most recent to oldest)

project 4
Extend the functionality of project 3 to incororate functions that encapsulate the four actions to take:
- Input a complete weather reading.
- temperature
- wind speed
- wind direction
- print the current weather
- If the user hasnt entered any data then print a message to that effect
- Exit the program
Add error checking on user inputs
Was This Post Helpful? 0
  • +
  • -

#9 snoopy11  Icon User is offline

  • Engineering ● Software
  • member icon

Reputation: 1378
  • View blog
  • Posts: 4,320
  • Joined: 20-March 10

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 10:09 AM

The first thing you need to do is split everything into functions instead of cramming everything into main()

Then call the functions one by one from main()
The three functions should be called

Temperature()
Wind()
&
Weather_Measurement()


You will need to figure out what parameters each function takes and what it should return.
This is why you should never cram everything into main() and should always follow good design principles.

You have really done this to yourself by bad design now you will have to break apart your program and refactor it into functions I recommend if using VS is that you start a new instance of VS and start again with a clean new project copying over the snippets that are still relevant from the old project, the results from user inputs should be stored in a dynamic container such as a std::vector simply to keep track of all the possible inputs.


At the moment

cout << "Enter the temperature:";
39
cin >> temp1.temperatures[0];




Your storing all the temperatures in the temperature array at position 0, what is the design thinking behind that move ?
Was This Post Helpful? 0
  • +
  • -

#10 11ash1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 25-October 15

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 10:37 AM

******Edit excessive quote removed*****


Well this is beginner for C++ and the previous assignments never taught us about seperating code or anything so I did not think it was necessary to seperate code.

This post has been edited by snoopy11: 03 November 2017 - 10:52 AM
Reason for edit:: excessive quote from me snoopy11 removed

Was This Post Helpful? 0
  • +
  • -

#11 snoopy11  Icon User is offline

  • Engineering ● Software
  • member icon

Reputation: 1378
  • View blog
  • Posts: 4,320
  • Joined: 20-March 10

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 10:56 AM

Well first of all you dont need to quote me or any one just use the fast reply area.


Secondly I get all that but you should always at least try to get your main as concise and neat as possible.

Thirdly the real question was this....

cout << "Enter the temperature:";
39
cin >> temp1.temperatures[0];





Your storing all the temperatures in the temperature array at position 0, what is the design thinking behind that move ?
Was This Post Helpful? 0
  • +
  • -

#12 11ash1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 25-October 15

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 11:12 AM

There really wasn't. I was only aiming for it to work. It works, but I guess the design is poor. I thought it was fine because I got hundreds on all the previous projects.
Was This Post Helpful? 0
  • +
  • -

#13 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2014
  • View blog
  • Posts: 5,397
  • Joined: 27-December 05

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 11:29 AM

View Post11ash1, on 03 November 2017 - 11:17 AM, said:

project 4
Extend the functionality of project 3 to incororate functions that encapsulate the four actions to take:

If you got 100 on Project 4 your teacher doesn't get 100. That assignment says clearly that the user's actions should be encapsulated in functions. And it is impossible to do Project 7 without doing that first.

It would be very difficult and confusing to try to modify your existing program to comply with that requirement, so as snoopy11 said, the easiest approach would be to start over.

(I still don't know what the third item -- "weather measurement" -- means in this context.)
Was This Post Helpful? 0
  • +
  • -

#14 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 5899
  • View blog
  • Posts: 20,141
  • Joined: 05-May 12

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 12:17 PM

If I understand what the teacher is asking for, it's quite simple really. In pseudo code:
class Temperature
{
    // store temperature here

    // have method(s) to print value
}

class Wind
{
    // store wind speed and direction here

    // have method(s) to print value
}

class WeatherMeasurement
{
    Temperature temperature;
    Wind        wind;

    // have method(s) to print the temperature and wind values.
}


Was This Post Helpful? 0
  • +
  • -

#15 snoopy11  Icon User is offline

  • Engineering ● Software
  • member icon

Reputation: 1378
  • View blog
  • Posts: 4,320
  • Joined: 20-March 10

Re: How To Encapsulate Functions In Code?

Posted 03 November 2017 - 12:22 PM

Yes you could use that design pattern however the instructions say to use structs,

At the very least I would have liked something along these lines.... not necessarily this but similar


#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;

struct Weather_Station
{
	string name;
	double temperature;
	double windspeed;
	string windDirection;
};

string DisplayMenu(string station_name)
{
	string str, temp;
	
	do
	{
		cout << "*******************WEATHER STATION: " << station_name << " *******************"<< endl << endl;

		cout << "I. Input a complete weather reading." << endl;
		cout << "P. Print the current weather." << "\n";
		cout << "H. Print the weather history (from most recent to oldest)." << endl;
		cout << "E. Exit the program." << "\n";
		cout << "Enter your choice: " << endl;

		cin >> str;
		temp = str;
		for (std::string::size_type i = 0; i < str.length(); ++i)
			temp[i] = toupper(str[i]);
		str = temp;

	} while (!(str == "I" || str == "P" || str == "H" || str == "E"));

	return str;
}

double getTemperature()
{
	double temp;
    string temp_string;
	stringstream converter;
	cout << "Enter the temperature: ";
	cin >> temp_string;
	converter << temp_string;
	converter >> temp;

	return temp;

};

int main()
{
	//Have the user provide a name for the weather station upon entry.
	vector<Weather_Station> myStation;
	Weather_Station myWeather_Details;
	string station_name, input_choice;
	cout << "Enter the name of Weather Station: ";
	getline(cin, station_name);
	myWeather_Details.name = station_name;
	//Control loop to perform various actions

	input_choice = DisplayMenu(station_name);
	
	if (input_choice == "I")
	{
		// get the details
		myWeather_Details.temperature= getTemperature(); // get temperature
		// TODO implement windspeed and wind direction functions
	}

	//store the details
	myStation.push_back(myWeather_Details);
	return 0;
}


Then you could have easily split the functions into multiple .h and .cpp files
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3