One word: Constructors
Code:
#include <cstring>
#include <iostream>
struct CandyBar
{
char brand[20];
float weight;
int calories;
CandyBar()
{
brand[0] = '\0';
weight = 0;
calories = 0;
}
CandyBar ( char name[], float wt, int cal )
{
std::strcpy ( brand, name );
weight = wt;
calories = cal;
}
};
int main()
{
CandyBar* p_candy = new CandyBar[3];
p_candy[0] = CandyBar ( "Chunky", 3.5f, 200 );
p_candy[1] = CandyBar ( "Monkey", 3.4f, 100 );
p_candy[2] = CandyBar ( "Choco", 3.3f, 50 );
for ( int i = 0; i < 3; i++ )
std::cout<< p_candy[i].brand <<": "<< p_candy[i].weight <<" -- "<< p_candy[i].calories <<std::endl;
}
Of course, that just automates the task of assigning values. You could do away with them (despite their convenience) with relative ease:
Code:
#include <cstring>
#include <iostream>
struct CandyBar
{
char brand[20];
float weight;
int calories;
};
int main()
{
CandyBar* p_candy = new CandyBar[3];
std::strcpy ( p_candy[0].brand, "Chunky" );
p_candy[0].weight = 3.5f;
p_candy[0].calories = 200;
std::strcpy ( p_candy[1].brand, "Monkey" );
p_candy[1].weight = 3.4f;
p_candy[1].calories = 100;
std::strcpy ( p_candy[2].brand, "Choco" );
p_candy[2].weight = 3.3f;
p_candy[2].calories = 50;
for ( int i = 0; i < 3; i++ )
std::cout<< p_candy[i].brand <<": "<< p_candy[i].weight <<" -- "<< p_candy[i].calories <<std::endl;
}
>char brand[20];
The array for a brand name is a little disconcerting. C-style strings are error prone and difficult to work with. You would be much happier using C++ strings:
Code:
#include <iostream>
#include <string>
struct CandyBar
{
std::string brand;
float weight;
int calories;
};
int main()
{
CandyBar* p_candy = new CandyBar[3];
p_candy[0].brand = "Chunky";
p_candy[0].weight = 3.5f;
p_candy[0].calories = 200;
p_candy[1].brand ="Monkey";
p_candy[1].weight = 3.4f;
p_candy[1].calories = 100;
p_candy[2].brand = "Choco";
p_candy[2].weight = 3.3f;
p_candy[2].calories = 50;
for ( int i = 0; i < 3; i++ )
std::cout<< p_candy[i].brand <<": "<< p_candy[i].weight <<" -- "<< p_candy[i].calories <<std::endl;
}
>float weight;
This is fine if you understand that C++ defaults to double just about everywhere, this includes literal values, so you'll need to postfix them with f as in this code:
Code:
p_candy[0].weight = 3.5f; // The f in 3.5f forces 3.5 to be float
>or give the structure a member function to set the values: <snip intermediate level code>
now keep in mind I'm fairly new to C++.