LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Whats wrong with this? (http://www.linuxquestions.org/questions/programming-9/whats-wrong-with-this-62215/)

OlRoy 05-28-2003 01:17 AM

Whats wrong with this?
 
I'm doing some examples in my C++ book and can't figure out how to create a array of a structure using new when there are different variable types in the structure. I'm getting a "Expression syntax" message (among others :) )in Borland C++ 6 Pro

#include <clx.h>
#include <iostream>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused

struct CandyBar
{
char brand[20];
double weight;
short int calories;
};
int main(int argc, char* argv[])
{


CandyBar * ptr = new CandyBar [3];
ptr[0] = {"Mocah Munch", 2.3, 350};
ptr[1] = {"Snickers", 3.1, 431};
ptr[2] = {Hershey", 1.9, 257};
std::cout << "Candy Bar Statistics\n\n";
//Mocah Munch
std::cout << "Brand: " << ptr[0].brand << "\n";
std::cout << "Weight: " << ptr[0].weight << "\n";
std::cout << "Calories: " << ptr[0].calories << "\n\n";
//Snickers
std::cout << "Brand: " << ptr[1].brand << "\n";
std::cout << "Weight: " << ptr[1].weight << "\n";
std::cout << "Calories: " << ptr[1].calories << "\n\n";
//Hershey
std::cout << "Brand: " << ptr[2].brand << "\n";
std::cout << "Weight: " << ptr[2].weight << "\n";
std::cout << "Calories: " << ptr[2].calories << "\n\n";
std::cin.get();
std::cin.get();
return 0;
}

Looking_Lost 05-28-2003 03:53 AM

here's one way:

#include<iostream>

using namespace std;

struct CandyBar
{
char* brand;
double weight;
short int calories;
};

int main(int argc, char* argv[])
{

CandyBar* ptr= new CandyBar [3];


ptr[0].brand="Mocah Munch";
ptr[0].weight=2.3;
ptr[0].calories=350;

ptr[1].brand="Snickers";
ptr[1].weight=3.1;
ptr[1].calories=431;

ptr[2].brand="Hershey";
ptr[2].weight=1.9;
ptr[2].calories=257;

cout << "Candy Bar Statistics\n\n";

for(int i=0; i<3; i++)
{
cout << "Brand: " << ptr[i].brand << "\n";
cout << "Weight: " << ptr[i].weight << "\n";
cout << "Calories: " << ptr[i].calories << "\n\n";
}


return 0;
}

OlRoy 05-28-2003 01:21 PM

That works, thank you


All times are GMT -5. The time now is 08:42 AM.