Hi, I am a new c++ programmer. I just learned about structures and pointers, get() and getline(). I recently came across a problem in the book I am following, that I wasn't able to solve. Here goes:
The CandyBar structure contains three members. The first member holds the brand
name of a candy bar. The second member holds the weight (which may have a fractional part) of the candy bar, and the third member holds the number of calories (an integer value) in the candy bar.
Write a program that creates an array of three CandyBar structures (use new to allocate the array dynamically), initializes them to values of your choice, and then displays the contents of each structure.
Here's my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
// candybar3.cpp -- declaring an array of three candybar structures with new
#include <iostream>
#include <cstring>
using namespace std;
struct candybar
{
char brand[20];
double weight;
int calories;
};
int main()
{
using namespace std;
int size;
cout << "Enter the 3 as the size of the array: ";
cin >> size;
candybar *snack = new candybar[size];
cout << "Enter the elements of the first array: ";
cin.get(snack->brand, 20);
cin.get();
cin >> snack[0].weight;
cin >> snack[0].calories;
cout << endl;
cout << "Enter the elements of the second array: ";
cin.get(snack->brand, 20);
cin >> snack[1].weight;
cin >> snack[1].calories;
cout << endl;
cout << "Enter the elements of the third array: ";
cin.get(snack->brand, 20);
cin >> snack[2].weight;
cin >> snack[2].calories;
cout << endl;
cout << "The elements of the first array are: ";
cout << snack[0].brand;
cout << snack[0].weight;
cout << snack[0].calories;
cout << endl;
cout << "The elements of the second array are: ";
cout << snack[1].brand;
cout << snack[1].weight;
cout << snack[1].calories;
cout << endl;
cout << "The elements of the third array are: ";
cout << snack[2].brand;
cout << snack[2].weight;
cout << snack[2].calories;
cout << endl;
return 0;
}
|
Although I am not getting any errors when I compile, I am not getting the right answer. I just learned about structures and pointers, and don't feel confident enough in this. So, I am not really sure what I am doing, but I tried. I need help solving this problem, and more importantly, I need help understanding structures - how and when to use them, how to display the contents of the structure etc.
Thanks in advance.