// Structures
struct CandyBar
{
// Brand name of candy bar
char brandName[arSize];
// Weight of candy bar ( could be fractional )
float weight;
// Number of calories
int calories;
};
CandyBar snack =
{
"Mocha Munch",
2.3f,
350
};
Displaying the contents of a structure?
Hi. Is there a way to display the contents of a structure. Like, would I have to use a pointer? Here''s the code...I want to display the value of the snack variable (which is of type CandyBar):
cout << snack.brandName << " has " << snack.calories << " per " << snack.wieght << " grams." << endl;
To you it''s a Bently, to me it''s a blue car...
"Diddy"
P.Diddy
I know how to do that, but is there a way to do it without having to say snack.brandName etc...
you could put a toString() function if you use classes... otherwise i think you have to do it member-by-member...
--- krez (krezisback@aol.com)
--- krez (krezisback@aol.com)
how mush easier do you want it ?
"I pity the fool, thug, or soul who tries to take over the world, then goes home crying to his momma."
- Mr. T
"I pity the fool, thug, or soul who tries to take over the world, then goes home crying to his momma."
- Mr. T
struct CandyBar{// struct access public by default// other declarations... friend ostream &operator<< (ostream &os, CandyBar &bar);private: char brandName[arSize]; float weight; int calories;};ostream &operator<< (ostream &os, CandyBar &bar){ // note we do not append endl. leave that to calling routine os << brandName << " has " << calories << " calories per " << weight << " grams.";}
You can now write:
CandyBar g = {/*fill in initialization*/};cout << g << endl;
To you it''s a Bently, to me it''s a blue car...
"Diddy"
P.Diddy
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement