There are many instances in programming where we need more than one variable in order to represent something. For example, to represent yourself, you might want to store your name, your birthday, your height, your weight, or any other number of characteristics about yourself. You could do so like this:
char strName[20]; int nBirthYear; int nBirthMonth; int nBirthDay; int nHeight; // in inches int nWeight; // in pounds
However, you now have 6 independent variables that are not grouped in any way. If you wanted to pass information about yourself to a function, you’d have to pass each variable individually. Furthermore, if you wanted to store information about more people, you’d have to declare 6 more variables for each additional person! As you can see, this can quickly get out of control.
Fortunately, C++ allows us to create our own user-defined aggregate data types. An aggregate data type is a data type that groups multiple individual variables together. One of the simplest aggregate data type is the struct. A struct (short for structure) allows us to group variables of mixed data types together into a single unit.
Because structs are user-defined, we first have to tell the compiler what our struct looks like before we can begin using it. To do this, we declare our struct using the struct keyword. Here is an example of a struct declaration:
struct Employee
{
int nID;
int nAge;
float fWage;
};
This tells the compiler that we are defining a struct named Employee. The Employee struct contains 3 variables inside of it: two ints and a float. These variables are called members (or fields). Keep in mind that the above is just a declaration — even though we are telling the compiler that the struct will have variables, no memory is allocated at this time.
In order to use the Employee struct, we simply declare a variable of type Employee:
Employee sJoe;
sJoe is a variable of type Employee. As with normal variables, declaring a variable allocates memory for that variable. Typically, the size of a struct is the sum of the size of all it’s members. In this case, since each integer is 4 bytes and a float is 4 bytes, Employee would be 12 bytes. However, some platforms have specific rules about how variables must be laid out in memory — consequently, the compiler may leave gaps between the variables. As a result, we can say the struct will be at minimum 12 bytes.
To find out the exact size of Employee, we can use the sizeof operator:
cout << "The size of Employee is " << sizeof(Employee);
On the author’s Pentium 4, this prints The size of Employee is 12.
When we declare a variable such as Employee sJoe, sJoe refers to the entire struct (which contains the member variables). In order to access the individual members, we use the member selection operator (which is a period). As with normal variables, struct member variables are not initialized, and will typically contain junk. We must initialize them manually. Here is an example of using the member selection operator to initialize each member variable:
Employee sJoe; sJoe.nID= 14; // initialize nID within sJoe sJoe.nAge = 32; // initialize nAge within sJoe sJoe.fWage = 24.15; // initialize fWage within sJoe
It is possible to declare multiple variables of the same struct type:
Employee sJoe; // create an Employee struct for Joe sJoe.nID = 14; sJoe.nAge = 32; sJoe.fWage = 24.15; Employee sFrank; // create an Employee struct for Frank sFrank.nID = 15; sFrank.nAge = 28; sFrank.fWage = 18.27;
In the above example, it is very easy to tell which member variables belong to Joe and which belong to Frank. This provides a much higher level of organization than individual variables would. Furthermore, because the members all have the same name, this provides consistency across multiple variables of the same type.
Struct member variables act just like normal variables, so it is possible to do normal operations on them:
int nTotalAge = sJoe.nAge + sFrank.nAge;
if (sJoe.fWage > sFrank.fWage)
cout << "Joe makes more than Frank" << endl;
// Frank got a promotion
sFrank.fWage += 2.50;
// Today is Joe's birthday
sJoe.nAge++;
Another big advantage of using structs over individual variables is that we can pass the entire struct to a function that needs to work with the members:
#include <iostream>
void PrintInformation(Employee sEmployee)
{
using namespace std;
cout << "ID: " << sEmployee.nID << endl;
cout << "Age: " << sEmployee.nAge << endl;
cout << "Wage: " << sEmployee.fWage << endl << endl;
}
int main()
{
Employee sJoe; // create an Employee struct for Joe
sJoe.nID = 14;
sJoe.nAge = 32;
sJoe.fWage = 24.15;
Employee sFrank; // create an Employee struct for Frank
sFrank.nID = 15;
sFrank.nAge = 28;
sFrank.fWage = 18.27;
// Print Joe's information
PrintInformation(sJoe);
// Print Frank's information
PrintInformation(sFrank);
return 0;
}
In the above example, we pass an entire Employee struct to PrintInformation(). This prevents us from having to pass each variable individually. Furthermore, if we ever decide to add new members to our Employee struct, we will not have to change the function declaration or function call!
PrintInformation() uses the Employee struct passed to it to print out employee information to the screen. The above program outputs:
ID: 14 Age: 32 Wage: 24.15 ID: 15 Age: 28 Wage: 18.27
Structs can contain other structs. For example:
struct Company
{
Employee sCEO; // Employee is a struct within the Company struct
int nNumberOfEmployees;
};
Company sMyCompany;
In this case, if we wanted to know what the CEO’s salary was, we simply use the member selection operator twice: sMyCompany.sCEO.fWage;
This selects the sCEO member from sMyCompany, and then selects the fWage member from within sCEO.
Initializer lists
Initializing structs member by member is a little cumbersome, so C++ supports a faster way to initialize structs using an initializer list. This allows you to initialize some or all the members of a struct at declaration time.
struct Employee
{
int nID;
int nAge;
float fWage;
};
Employee sJoe = {1, 42, 60000.0f}; // nID=1, nAge=42, fWage=60000.0
You can use nested initializer lists for nested structs:
struct Employee
{
int nID;
int nAge;
float fWage;
};
struct Company
{
Employee sCEO; // Employee is a struct within the Company struct
int nNumberOfEmployees;
};
Company sCo1 = {{1, 42, 60000.0f}, 5};
A few final notes on structs
The “m_” Hungarian Notation prefix for members is typically not used for structs, even though structs contain members. This is (in part) because all variables in a struct are members! Consequently, labeling them with a “m_” prefix is somewhat redundant.
It is common to declare structs in a header file, so they can be accessed by multiple source files.
The class aggregate data type builds on top of the functionality offered by structs. Classes are at the heart of C++ object-oriented programming. Understanding structs is the first step towards object-oriented programming!
Quiz
1) You are running a website, and you are trying to keep track of how much money you make per day from advertising. Declare an advertising struct that keeps track of how many ads you’ve shown to readers, what percentage of users clicked on ads (as a floating point number between 0 and 1), and how much you earned on average from each ad that was clicked. Read in values for each of these fields from the user. Pass the advertising struct to a function that prints each of the values, and then calculates how much you made for that day (multiply all 3 fields together).
2) Write a struct to hold a fraction. The struct should have a integer numerator and a integer denominator member. Declare 2 fraction variables and read them in from the user. Write a function called multiply that takes both fractions, multiplies them together, and prints the result out as a decimal number.
Quiz Answers
5.1 — Control flow introduction
|
Index
|
4.6 — Typedefs
|
5.1 — Control flow introduction
Index
4.6 — Typedefs
[...] better correspond to the problem being worked upon. You have already seen how enumerated types and structs can be used to create your own custom data [...]
Is there a ‘with’ keyword that allows you to edit variables of a structure without having to re-type the name repeatedly [like in Visual Basic]?
Employee sFrank //a variable of the Employee type
with sFrank
.nEmployeeID = 15
.nAge = 28
[end with statement]
// or something like that?
Not that I’m lazy or anything…
PS: I think there are some unwanted borders/shading on this page.
Bye!
Nope, there is no “with” keyword, nor any keyword that mimics that kind of functionality.
[...] 4.7 — Structs [...]
/* Program of Structure Exerice 1 */
#include <iostream.h>
#include <conio.h>
struct web
{
int adv;
float rate;
float click;
};
float money(int adv,float rate,float click)
{
float totalearning;
totalearning = (adv * rate * click);
return totalearning;
}
web mny;
void main()
{
float res;
clrscr();
cout << "n How many advertise was shown: ";
cin >> mny.adv;
cout << "n What was rate of click : ";
cin >> mny.rate;
cout << "n Average of earning per click : ";
cin >> mny.click;
res = money(mny.adv , mny.rate , mny.click);
cout << "n The Total earning is " << res;
getch();
}
/* End of Program */
We can pass a structure to a function.
But can a function return a structure of data?
Cheers.
Yes, a function can return a structure of data. This is one of the few ways to return multiple values from a function.
Is there such a thing like typedef pointers? I got into trouble to initialize PCOORD. Finally I figured it out but I am not sure that am I doing the right thing? I thought it would be good to put this code example here since the mechanism is used in many places.
For example (code):
typedef struct Coordinate
{
short X;
short Y;
} COORD, *PCOORD;
int main()
{
COORD pos;
pos.X = 0;
pos.Y = 0;
PCOORD pPos = &pos;
}
At the beginning my main function looked like the main() below:
int main()
{
//this is the wrong way to do things
PCOORD pPos;
pPos->X = 0;
pPos->Y = 0;
//if you use pPos now in somewhere compiler gives you warning that pPos is not initialized and my program crashed if I run that.
// Why is it so? Why I cant initialize?
}
Yes, you can do this — PCOORD is a typedef’s poniter to a Coordinate struct. You can’t initialize your pPos because pPos is a pointer, and you haven’t set it to point at anything.
#include<iostream.h> struct Score { int nScore; }; void ReadScore(Score s1) { cout<<"\nEnter Score:"; cin>>s1.nScore; } void PrintScore(Score s1) { cout<<"\nScore="<< s1.nScore; } int main() { Score s1; ReadScore(s1); PrintScore(s1); return 0; }When i print the score i got junk , i understood since initially s1 was not initialised, and
when it is passed to function ReadScore s1 now become a local scope for that function and
value got destroyed after the function ends and dats y i got junk value.
But When i am doing like this
#include<iostream.h> struct Score { int nScore; }; void ReadScore(Score s1) { Score s2; cout<<"\nEnter Score:"; cin>>s2.nScore; s1 =s2; } void PrintScore(Score s1) { cout<<"\nScore="<< s1.nScore; } int main() { Score s1; ReadScore(s1); PrintScore(s1); return 0; }i m still getting junk.Well i have created another structure variable s2, and then i assigned
s2 to s1, so it will be copying the score, Correct??? then y the value is getting destroyed after the f
the function ends
This is probably old but I’ll answer it anyway, for future reference.
ReadScore doesn’t return the s1 struct. Since s1 is declared locally in both the main function and the ReadScore function, it’s two separate Score structs. Therefore, when you called ReadScore, it didn’t change the value of main()s s1 Score struct. To change that code to work right, you’d either need to use pointers, or you could return the struct from ReadScore. The following examples exclude your other perfectly fine function and struct declaration.
Returning struct:
Score ReadScore() { cout << "\nEnter Score: "; Score s1; cin >> s1.nScore; return s1; } int main() { Score s1; s1 = ReadScore(); PrintScore(s1); return 0; }Or you could use pointers:
void ReadScore(Score* s1) { cout << "\nEnter Score: "; cin >> s1->nScore; } int main() { Score s1; ReadScore(&s1); PrintScore(s1); return 0; }Hope that helps!
Okay i understood what can go wrong in the above problem???correct me if i am wrong!!
when i declare Score s1; memory has been allocated lets say its address is 123.
Now when i am passing this s1 to the function ReadScore, this function will create a copy of s1
which will have different memory,(let say its address is 125) so it does everything right,
but doesnt touch at all the address 123..which is still junk. SO i m getting junk correct?
the above problem i overcame ,when i send the reference of the s1!!!
Or else i can call the PrintScore inside the ReadScore function..this will also eliminates the problem.
Exactly! This is a pass-parameter-by-value-or-reference issue. As a general rule: if you need to modify the struct/obj and keep changes in the previous scope, pass by reference, not by value. Your description of what was happening in your code is spot on.
I have see that some people define structs this way
struct something { int x; int y } somethingWhat I dont understand is, why they write “something” two times?
It’s easier to understand when you use different labels:
struct something { int x; int y; } somethingelse;In this case, something is the name of the struct itself. It’s like naming a function, it’s just a label to reference it by later. This doesn’t actually create a struct object, it just lays out what a struct looks like.
somethingelse declares an actual struct object. It is a variable that takes up memory.
So when you see something like this:
struct something { int x; int y; } something;It basically means you’re defining a struct named something, and then also defining a local variable with the same name. In my opinion, this is bad coding style since you’re using the same name for two different things.
Usually when I see this, it’s because people want a “one off” struct — something that’s only used once. In that case, you can just use an anonymous struct:
struct { int x; int y; } something;This struct has no name and the type can never be referenced directly. However, something is a variable of that type.
I believe you have a mistake in your PrintInformation() example. The function tries to print the variable nID within sEmployee, but the ID variable was declared as nEmployeeID in the Employee struct.
Extremely helpful tutorials, thanks!
[ Fixed! Thanks for letting me know. -Alex ]
#include void PrintInformation(Employee sEmployee) { using namespace std; cout << "ID: " << sEmployee.nID << endl; cout << "Age: " << sEmployee.nAge << endl; cout << "Wage: " << sEmployee.fWage << endl << endl; } int main() { Employee sJoe; // create an Employee struct for Joe sJoe.nID = 14; sJoe.nAge = 32; sJoe.fWage = 24.15; Employee sFrank; // create an Employee struct for Frank sFrank.nID = 15; sFrank.nAge = 28; sFrank.fWage = 18.27; // Print Joe's information PrintInformation(sJoe); // Print Frank's information PrintInformation(sFrank); return 0; }This example does not work for me :S
I get a lot of errors, first of which says “error: variable or field ‘PrintInformation’ declared void”
And then a bunch of scope errors… :S I’m using Code::Blocks. Any idea why this is happening?
1) you need #include
2) you need to include struct then define Employee
3) you need to include a void for each employee, so replace ‘sEmployee’ with the employee’s names and include both in the one void to make it simpler.
4) I’m guessing alex didn’t want to make this example one of those “do it with me’s” he also has two void calls for each employee, while you could include both in one, this is what it would be like if you included both in one void…
#include
using namespace std;
struct Employee //this is where you forgot to include the struct and define “Employee
{
int nID;
int nAge;
float fWage;
};
void PrintInformation(Employee sFrank, Employee sJoe) //both employees are in one void.
{
using namespace std;
cout << “ID: ” << sFrank.nID << endl; //Frank starts here.
cout << “Age: ” << sFrank.nAge << endl;
cout << “Wage: ” << sFrank.fWage << endl << endl;
cout << “ID: ” << sJoe.nID << endl; //Joe stats here.
cout << “Age: ” << sJoe.nAge << endl;
cout << “Wage: ” << sJoe.fWage << endl << endl;
}
int main()
{
Employee sJoe;
sJoe.nID = 14;
sJoe.nAge = 32;
sJoe.fWage = 24.15;
Employee sFrank;
sFrank.nID = 15;
sFrank.nAge = 28;
sFrank.fWage = 18.27;
PrintInformation(sFrank, sJoe); // The void is called here.
return 0;
}
It would probably be a better idea to void the two separately because they’re different subjects, but for the sake if it being an example I just decided to explain both.
And I also use Code Blocks, its a great IDE!
Hope this cleared it up for you.
Hello can any body debug following code.Its not running for me… having lot of errors..
thanks in advance
#include
#include “stdafx.h”
void PrintInformation(Employee sFrank, Employee sJoe)
{
using namespace std;
cout << “ID: ” << sFrank.nID << endl;
cout << “Age: ” << sFrank.nAge << endl;
cout << “Wage: ” << sFrank.fWage << endl << endl;
cout << “ID: ” << sJoe.nID << endl;
cout << “Age: ” << sJoe.nAge << endl;
cout << “Wage: ” << sJoe.fWage << endl << endl;
}
int main()
{
using namespace std;
struct Employee
{
int nID;
int nAge;
float fWage;
};
Employee sJoe;
sJoe.nID = 14;
sJoe.nAge = 32;
sJoe.fWage = 24.15;
Employee sFrank;
sFrank.nID = 15;
sFrank.nAge = 28;
sFrank.fWage = 18.27;
PrintInformation(sFrank, sJoe);
return 0;
}
why can’t I print the CEO’s data this way. I think I am doing some silly mistake…
#include <iostream> using namespace std; struct Employee { int nID; int nAge; float fWage; }; struct Company { Employee sCEO; int nNumberOfEmployees; }; void PrintInformation(Employee sEmployee) { cout << "ID: " << sEmployee.nID << endl; cout << "Age: " << sEmployee.nAge << endl; cout << "Wage: " << sEmployee.fWage << endl << endl; } int main() { Employee sJoe; sJoe.nID=20; sJoe.nAge=32; sJoe.fWage=12.5; PrintInformation(sJoe); Company sMyCompany; sMyCompany.sCEO.nID=001; sMyCompany.sCEO.nAge=48; sMyCompany.sCEO.fWage=22.5; PrintInformation(sCEO); return 0; }U are actually passing the structure sCEO which is not declared . So the compiler gives u an error . Since the sCEO is a member of sMyCompany. U should use sMyCompany.sCEO in order to access the structure of Employee sCEO .
The following line would fix ur problem
PrintInformation(sMyCompany.sCEO);
instead of
PrintInformation(sCEO);
Is it possible to create multiple structs using a for loop?
struct sDie { int nFace; int nSides; }; int nDice = 5; for (int iii = 1; iii <= nDice; iii++) { sDie iii; sDie.iii.nFace = iii; sDie.iii.nSides = 6; };Nevermind about that last comment. I realized that there was a following article in this tutorial that explains how to accomplish this.
My code prints out “e” for the name of the football player. I want it to print “Jake”.
Notice that I use cName[15] to allow enough space for the name. This is probably my mistake.
Everything else prints correctly. Below are the pertinent chunks of code:
struct FootballPlayer { char cName[15]; int nVertLeap; int nBenchPress; float fFortyDash; }; void PrintStats(FootballPlayer sPlayer) { cout << "Player's Name is " << sPlayer.cName[15] << endl; cout << "Vertical Leap = " << sPlayer.nVertLeap << " inches" << endl; cout << "225lb Bench Press = " << sPlayer.nBenchPress << " presses" << endl; cout << "Forty Yard Dash = " << sPlayer.fFortyDash << " seconds" << endl; } FootballPlayer sJake; sJake.cName[15] = 'Jake'; sJake.nVertLeap = 30; sJake.nBenchPress = 28; sJake.fFortyDash = 4.4;you’ve got one problem I see in your code there:
in the method “PrintStats”, the first cout-line: You are printing out cName[15]. Why? first of all, you want the name and not just one character that would reside in “slot” 15. Second: Your array of chars “cName” only has “slots” up to number 14. You created it with a [15], so you have to access the slots with the numbers 0 – 14. That makes 15 slots. (i.e. Chars in that Array)
When I understand the solution for 1) right, this is showing us a style of coding this tutorial itself said we should not do.
The method PrintAdvertising() get’s passed a struct named sAd, while the main-function declares a struct with the name sAd.
So while in the PrintAdvertising() method, the local sAd is hiding the main()-sAd.
Am I right or did I understand something wrong? Thx!
Alex
for the quiz 2 how-come the same result is not produced?
the correct answer is printed in the above code
but it just prints 0, in the next code, i know i am doing something wrong with type casting, but what exactly am i doing wrong
thanks
Hello Alex,
I have trouble understanding the following situation, where a struct consisting of int, float and bool types shows a complete size as 12. Whereas, if I display the size of each data-type, it shows 4(int), 4(float), 1(bool).
Please explain.
The code:
#include <iostream> using namespace std; int main() { struct Person { int age; float wage; bool sex; }; Person Mayur; cout << sizeof(int) << endl; cout << sizeof(float) << endl; cout << sizeof(bool) << endl; cout << sizeof(Person) << endl; cout << sizeof(Mayur) << endl; return 0; }The Output:
Regards,
Mayur
Let me quote Alex and highligth the important bit that you wonder about:
“Typically, the size of a struct is the sum of the size of all it’s members. In this case, since each integer is 4 bytes and a float is 4 bytes, Employee would be 12 bytes. However, some platforms have specific rules about how variables must be laid out in memory — consequently, the compiler may leave gaps between the variables. As a result, we can say the struct will be at minimum 12 bytes.”
Cheers
Ole
struct Fractions
{
int nNumerator;
int nDenominator;
};
int multiply(int x, int y)
{
return x * y;
}
float produceValue(Fractions sAny)
{
using namespace std;
cout << "Enter a Numerator " <> sAny.nNumerator;
cout << "Enter a Denominator " <> sAny.nDenominator;
return (float)sAny.nNumerator / sAny.nDenominator;
}
int main()
{
using namespace std;
cout << "Now, we are going to multiply two fractions. First: " << endl;
float x = produceValue;
cout << "Now, once again " << endl;
float y = produceValue;
cout << "The answer is " << multiply(float x, float y);
return 0;
}
didnt work though, does anyone know why?
Try this:
#include
#include
struct Fractions
{
int nNumerator;
int nDenominator;
};
float multiply(float x, float y)
{
return x * y;
}
float produceValue()
{
using namespace std;
Fractions sAny;
cout <> sAny.nNumerator;
cout <> sAny.nDenominator;
float result = (float)sAny.nNumerator / sAny.nDenominator;
return (result);
}
int main()
{
using namespace std;
cout << "Now, we are going to multiply two fractions. First: " << endl;
float x = produceValue();
cout << "Now, once again " << endl;
float y = produceValue();
cout << "The answer is " << multiply(x, y);
cin.clear();
cin.ignore(255, '\n');
cin.get();
return 0;
}
sorry i know didt put the brackets. It says that produceValue does not take 0 arguments
Shouldn’t structure alignment be mentioned in this chapter?
BTW, great free tutorials. Thanks for your effort.
#include “stdafx.h”
#include
struct advertising
{
int nAds_shown;
float percentThatclicked;
float averageEarned;
};
void read()
{
using namespace std;
advertising scompany;
cin >> scompany.nAds_shown;
cin >> scompany.percentThatclicked;
cin >> scompany.averageEarned;
}
int main(advertising scompany)
{
using namespace std;
read();
cout << scompany.nAds_shown << endl;
cout << scompany.percentThatclicked << endl;
cout << scompany.averageEarned << endl;
cout << scompany.nAds_shown*scompany.percentThatclicked * scompany.averageEarned << endl;
return 0;
}
This code compiles and links without a problem, but when I actually run it it returns very odd numbers.
Can anyone help?
Try making the void Read() function return the struct advertisementy like so:
#include <iostream> struct advertising { int nAds_shown; float percentThatclicked; float averageEarned; }; <b>advertising read() { using namespace std; advertising scompany; cin >> scompany.nAds_shown; cin >> scompany.percentThatclicked; cin >> scompany.averageEarned; return scompany; }</b> int main(advertising scompany) { using namespace std; scompany = read(); cout << scompany.nAds_shown << endl; cout << scompany.percentThatclicked << endl; cout << scompany.averageEarned << endl; cout << scompany.nAds_shown*scompany.percentThatclicked * scompany.averageEarned << endl; return 0; }What happens is that when you run through the function Read() it stores the data in the SCOPE, and than is destroyed after the function ends. So when you return scompany and store it into scompany on int main(), it passes the values to the main() scope. There might be a little more to it but basically the values are destroyed when Read() ends so you have to pass it on to main() which I have done. BTW I am unsure as to why you included stdafx.h when you have nothing in your program that needs that header, whats even more curious is the way you included it (with “” instead of ) and that it compiled at all.
In your “Quiz 1 Answer” You did not divide the percentage, or at least turn it into a decimal, so the output will be wrong.
For example:
5000 * 50 * $.15 = $37,500
5000 * (50 / 100) * $.15 = $375
The two are very different. The user will not know to put a decimal instead of a whole number (in fact they might even put a modulus after the number which is bad). I guess I am just a little nit-picky. BTW here is my answer if you are interested:
#include <iostream> #include <conio.h> using namespace std; struct Advertising { int nAds; float fPercentageClickedAds; float nAdsProfit; float fDailyProfit; }; Advertising DailyProfit(Advertising advertising) { advertising.fDailyProfit = (advertising.nAds * advertising.fPercentageClickedAds * advertising.nAdsProfit); return advertising; } int main() { Advertising advertising; cout << "n How many ads have you shown to readers? "; cin >> advertising.nAds; cout << "n What percentage of users clicked the ads? "; cin >> advertising.fPercentageClickedAds; advertising.fPercentageClickedAds /= 100; cout << "n How much did you earn for each ad clicked? "; cin >> advertising.nAdsProfit; advertising = DailyProfit(advertising); cout << "nn Your daily profit: $" << advertising.fDailyProfit; getch(); return 0; }k i have problem i tried to make a lot of programs but i get to the same point and get stuck. my problem is i have to codes they work fine, they have been tested.
i need something to execute one of the code
if the user entered a keyword.
so if the user entered c to f i want the
int nCtoF();.. execute but the other one dont.
hi, i am trying to write a program, using classes and structs and inheritence…
the program kind of represents a university system where tutors teach only specific modules and students are only enrolled on specific modules.
To store information about students and their modules.
the user is prompted to enter the number of modules they undertake and then according to the number they enter they get the option to store information about these modules.
for example if user enters 1 module only 1 struct is called to store the information
but if user enters 3 modules, the program should allow three struct objects to be entered..
i can’t get three structs to come if the user enters three….
and is using classes and struct the best option to solve this problem?
any help please….
I think that the most optimal way to do (using the less RAM space) would be as you said, using inheritance, and learn polymorphism might help you a lot ;) so you will actually will need classes, you can just avoid structs ;) but if it is about speed, then structs are better than classes…so think what do you want ;)
This is my answer for exercise 1 and 2 :
Exercise 1 :
#include <iostream> #include <conio.h> using namespace std; struct earn{ int ads_count ; double user_perc ; double average_inc ; }mysite; void dis_calc(earn x); int main() { double temp; cout << "Enter Number of ads : " ; cin >> mysite.ads_count ; cout << "Enter User Percentage (0-99%) : " ; cin >> temp ; mysite.user_perc = temp/100 ; cout << "Enter Av. Income : " ; cin >> mysite.average_inc ; system("cls"); dis_calc(mysite); getch(); return 0; } void dis_calc(earn x){ cout << "Total Ads No. : " << x.ads_count << endl ; cout << "User Percentage : " << x.user_perc << endl; cout << "Av. income : " << x.average_inc << endl; cout << "******************************" << endl; cout << "Today total income : " << endl; cout << "Today total income : " << x.ads_count*x.user_perc*x.average_inc << endl; }And Exercise 2 :
#include <iostream> using namespace std; struct frac{ double numerator ; double denominator ; }fract1,fract2; void multiply(frac x , frac y); int main() { cout << "Enter n and m in (n/m)." << endl; cout <<endl; cout << "Enter n for 1st fracion : " ; cin >> fract1.numerator ; cout << "Enter m for 1st fracion : " ; cin >> fract1.denominator ; cout << "Enter n for 2nd fracion : " ; cin >> fract2.numerator ; cout << "Enter m for 2nd fracion : " ; cin >> fract2.denominator ; system("cls"); multiply(fract1, fract2); return 0; } void multiply(frac x , frac y){ double a,b; cout << "1st fraction is : " << x.numerator <<"/"<<x.denominator << endl; cout << "2nd fraction is : " << y.numerator <<"/"<<y.denominator << endl; cout << endl; cout << "1st X 2nd : " << x.numerator*y.numerator <<"/"<<x.denominator*y.denominator << endl; a = x.numerator*y.numerator ; b = x.denominator*y.denominator ; cout << "1st X 2nd (in decimal) : " << a/b << endl ; }Hello Alex, I have a qst:
From your code:
struct Employee { int nID; int nAge; float fWage; };when you made the declaration of this:
shouldn’t be like this:
or making the struct a typedef?? :
typedef struct Employee { blabla...};I think it should be like that, so then you can declare sJoe as you did…
I hope that if you reply I will get to my inbox that you did it ;) so I can check what you wrote ;)
why does this give negative result?
// fraction.cpp : Defines the entry point for the console application.
//
#include “stdafx.h”
# include
struct sFraction
{
int nNumerator;
int nDenominator;
};
float Product( sFraction s1, sFraction s2)
{
float fResult;
fResult= static_cast (s1.nNumerator*s2.nNumerator)/static_cast (s1.nDenominator*s1.nDenominator);
return fResult;
}
int main()
{using namespace std;
sFraction sF1,sF2;
cout<<"input first nummerator"<> sF1.nNumerator;
cout << "input first denominator"<> sF1.nDenominator;
cout<<"input second numerator"<> sF2.nDenominator;
cout<< "input second denomirator"<> sF2.nDenominator;
cout << "the result is "<<Product (sF1,sF2)<<endl;
return 0;
}
Thanks a lot Alex
Really very useful tutorial on web. Thanks again for the effort :)
Would someone mind telling me why this is rounding down my answer? I’m not sure what i’m doing wrong.
#include "stdafx.h" #include <iostream> using namespace std; int main() { int numerator = 3; int denominator = 4; cout << static_cast<float>(numerator / denominator); return 0; }It’s giving me the answer 0, but i want 0.75.
I take it i accidently read over one of the earlier lessons which is really confusing me now.
I kinda doubt you’re still wondering this 2 months later, but in case you haven’t figured it out:
Because the / operator is in the parenthesis, the division is performed first. Both inputs are integers, so it is performed as an integer operation (and rounded to 0). Only after the division is complete does it convert the result to float. You want the division to be a float operation, so you should cast one of the inputs *before* the division, as follows:
This will make it a float operation, and it will not be rounded.
For the Example in the post, I tried the following
……
…….
int main()
{
struct Employee
{
int nID, nAge;
float fWage;
};
….
…..
As you can see, I defined struct inside main(). This failed. However, defining Struct outside main() worked? Any reason?
J
The variables inside the structure are treated as local variables inside main(). When you declare it outside main() they become global variables (evil) ;-)
It should work if you initialize your variables before calling a function.
Simply well explained tutorial. Thanks.
Alex,
You’ve shown that we can pass struct to functions, but here is a question :
Can a function return result of type struct?
cout << "Wage: " << sEmployee.fWage << endl << endl;
is there a reason for 2 endl's? or is it just a typo :)
why my code always produce interger output?Can anyone please help me?:(
// Enumeraor.cpp : Defines the entry point for the console application.
//
#include “stdafx.h”
#include
struct Fraction
{
int nNumerator;
int nDenomintor;
};
double Input()
{
using namespace std;
Fraction sFrac;
cout<<"Enter the numerator of fraction :"<>sFrac.nNumerator;
cout<<"Enter the denominator of fraction :"<>sFrac.nDenomintor;
return static_cast(sFrac.nNumerator/sFrac.nDenomintor);
}
int main()
{
using namespace std;
double dFracA=Input();
double dFracB=Input();
double dResult;
static_cast(dResult=dFracA*dFracB);
cout<<"The result is :"<<dResult<<endl;
return 0;
}
Because you need to choose a type to cast, e.g. static_cast(expression) instead of static_cast(expression).
html screwed my last comment :/
@Jman try this
first ur struct is an integer,and the function double, does that make sense?
Try something like this:
struct fraction
{
int nNumerator;
int nDenominator;
};
void input(fraction obj,int nNum,int nDenom)
{
obj.nNumerator=nNum;
obj.nDenominator=nDenom;
cout<<"the numerator "<<obj.nNumerato<<endl;
cout<<"the denominator"<<obj.nDenominator<<endl;
}
int main()
{
fraction objm;
int nNum1,nDenom1;
cout<<"enter the numerator"<>nNum1;
cout<<"enter the denominator"<>nDenom1;
//call to the function
input(objm,nNum1,nDenom1);
return 0;
}
hi
in quiz 2 i wrote the program :
#include
struct Fraction
{
float x;
float y;
float frac;
};
void Multiply(Fraction f1, Fraction f2)
{
using namespace std;
// Don’t forget the static cast, otherwise the compiler will do integer division!
cout << f1.frac*f2.frac ;
}
int main()
{
using namespace std;
// Allocate our first fraction
Fraction f1;
cout <> f1.x;
cout <> f1.y;
// Allocate our second fraction
Fraction f2;
cout <> f2.x;
cout <> f2.y;
f1.frac = f1.x/f1.y;
f2.frac =f2.x/f1.y;
Multiply(f1,f2);
return 0;
}
but my program has less accuracy than yours.
is this has a relation to this fact that i declare my variables first in float but u declare them first in int and then convert them to float?
Hi, I have to write code to do the following task:
–define a simple structs to store common information. In particular, write definitions for a struct called Point to store the X, Y and Z coordinates of a point.
I have this:
struct Point{
double xcoord;
double y coord;
};
Then Having defined a struct in the previous section, I need to write two simple functions to use this struct. First, write a function to prompt the user to enter the coordinates of a point, read the coordinates from the keyboard and store them a struct of type Point. The function prototype is as follows
Point ReadPoint();
Second, write a function to determine the Cartesian distance between two points. The function prototype is as follows
double DistanceBetweenPoints( const Point& pt1, const Point& pt2 );
I have:
Point ReadPoint(){
double x;
double y;
cout<<"enter the x and y coordinate of the point: "<>x>>y;
}
and
double DistanceBetweenPoints( const Point& pt1, const Point& pt2 ){
double distance;
distance= sqrt (pow((x1-x2),2)+pow((y1-y2),2));//i dont know what variables I should add in here
return double;
}
..Please help and respond ASAP because I need to have this assignment done soon..thanks!
[...] 1) Hide Solution [...]
[...] KNOWLEDGE FOR THIS SNIPPET Structs Classes Template Classes – What Are They? Stacks LIFO – What Is It? #include < stack> Linked Lists [...]
[...] homework assignment which was presented in an intro to programming class. This program utilizes a struct, which is very similar to the class concept. For this assignment, the class was asked to make a [...]
[...] KNOWLEDGE FOR THIS SNIPPET Structs Classes Template Classes – What Are They? Queue – What is it? FIFO – First In First Out #include [...]
Why can’t i use endline when asking for user input for the struct ?? It took me forever to figure out that’t the problem but why is it so please ?
This is such a great website. Thanks very much for these tutorials. They’re absolutely spot on.
Just one quick question. What would be the best way to make a struct declaration visible throughout the entire project. ie if you declared the struct type in one file and then wanted to create an instance of it in another.
Would it be good practice to use a separate file for creating all struct and then use an #include in each file where you need to use it?
Just thought I’d share my code like some people are:
First exercise, in main.cpp:
#include <iostream>#include "main.h"
using namespace std;
int main()
{
cout << "Hi there! Um, please enter the following:\n" <<
"-- Total ads shown to users\n" <<
"-- Percent of ads clicked\n" <<
"-- Average profit per ad" << endl;
Advertising sAds;
cin >> sAds.nAdsShown >>
sAds.fPercentClicked >>
sAds.fAverageProfit;
sAds.fPercentClicked /= 100; // Convert from percent to decimal so next calculation can occur
cout << "Total profit today: $" <<
(
sAds.nAdsShown *
sAds.fPercentClicked *
sAds.fAverageProfit
) << endl;
}
First exercise, main.h:
#ifndef MAIN_H#define MAIN_H
struct Advertising
{
int nAdsShown;
float fPercentClicked;
float fAverageProfit;
};
#endif
Second exercise, main.cpp:
#include <iostream>#include "main.h"
using namespace std;
int main()
{
Fraction sMyFrac, sYourFrac;
cin >> sMyFrac.nNumer >> sMyFrac.nDenom;
cin >> sYourFrac.nNumer >> sYourFrac.nDenom;
Fraction sProduct = multFractions(sMyFrac, sYourFrac);
printFraction(sProduct);
}
Fraction multFractions(Fraction sX, Fraction sY)
{
Fraction sProduct;
sProduct.nNumer = sX.nNumer * sY.nNumer;
sProduct.nDenom = sX.nDenom * sY.nDenom;
return sProduct;
//return (new Fraction{sX.nNumer * sY.nNumer, sX.nDenom * sY.nDenom}); // one-liner?
}
void printFraction(Fraction sFrac)
{
cout << static_cast<double>(sFrac.nNumer) / sFrac.nDenom;
}
Second exercise, main.h:
#ifndef MAIN_H#define MAIN_H
struct Fraction
{
int nNumer;
int nDenom;
};
Fraction multFractions(Fraction sX, Fraction sY);
void printFraction(Fraction sFrac);
#endif
[...] date and time. Knowledge of how this process works would be beneficial, but is not necessary. Click here for more information on how structs [...]
[...] KNOWLEDGE FOR THIS PROGRAM Functions Passing a Value By Reference Integer Arrays Structures Constant Variables Boolean [...]
something is wrong with my code, I try to modify the code, and here’s what i got, but then again, after typing the age, the program skip the Address and i don’t know what’s wrong with this code.
#include
using namespace std;
struct EmpInfo {
string sName;
int iEmpNo;
short iAge;
string sAddress;
float fWage;
} Emp;
void EmpPrint() {
cout <<"Name : " << Emp.sName << endl;
cout <<"Emp No : " << Emp.iEmpNo << endl;
cout <<"Age : " << Emp.iAge << endl;
cout <<"Address: " << Emp.sAddress << endl;
cout <<"Wage : " << Emp.fWage << endl;
}
int main()
{
cout <<"Size of Emp is : " << sizeof(Emp) <<endl <<endl;
cout <<"Enter name : "; getline(cin,Emp.sName);
cout <> Emp.iEmpNo;
cout <> Emp.iAge;
cout <<"Enter Address : "; getline(cin, Emp.sAddress);
cout <> Emp.fWage ;
cout << endl << endl;
EmpPrint();
return 0;
}
[...] KNOWLEDGE FOR THIS SNIPPET Structs Classes Template Classes – What Are They? Queue – What is it? FIFO – First In First Out #include [...]
[...] KNOWLEDGE FOR THIS PROGRAM Structs Classes Template Classes – What Are They? Stacks Queues LIFO – Last In First Out FIFO – First In [...]