casting enums

I learning how to transition from C to C++, and having problems with casting. I don't know how. Here's snippets of my code:

class RECORD
{
public:
char *number;
enum Type {box = 1, tank, flat} type;
int loaded;
char *desination;
};

RECORD *getCarInfo(void)
{
char buffer[MAXBUFFER], *ptrNumber, *ptrDestination;
int numBuffer;
RECORD *ptrCar;

//allocate memory for structure
ptrCar = (RECORD *)malloc(sizeof(RECORD));
ptrNumber = (char *)malloc(strlen(buffer) + 1);
ptrDestination = (char *)malloc(strlen(buffer)+1);

//exit on failure of memory allocation
if(!ptrCar || !ptrNumber || !ptrDestination)
{
fprintf(stderr, "Could not allocate memory!\n");
exit(1);
}

//get information and copy to structure
printf("CAR NUMBER: ");
gets(buffer);
strcpy(ptrNumber, buffer);
ptrCar->number = ptrNumber;

printf("WHAT TYPE?\n\t1)BOX\n\t2)TANK\n\t3)FLAT\n");
scanf("%d", &numBuffer);
//------------------------------------------------------------------
ptrCar->type = numBuffer; //here's the line with the problem
//------------------------------------------------------------------

printf("IS IT LOADED(y/n)? ");
scanf("%d", &numBuffer);
ptrCar->loaded = numBuffer;

printf("WHERE IS IT'S DESTINATION? ");
fflush(stdin); //flush stdin
gets(buffer);
strcpy(ptrDestination, buffer);
ptrCar->desination = ptrDestination;

return ptrCar;
}

Visual C++ Express is giving me this error:

error C2440: '=' : cannot convert from 'int' to 'RECORD::Type'
Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast)

I've tried:
ptrCar->type = (int) numBuffer;
ptrCar->type = int (numBuffer);

but it didn't work, and we haven't been taught about static_cast yet. Any ideas? Thanks




Last edited on
closed account (z05DSL3A)
ptrCar->type = static_cast<RECORD::Type>(numBuffer); explicit cast: static_cast

ptrCar->type = (RECORD::Type)numBuffer; explicit cast: C-style cast

ptrCar->type = RECORD::Type(numBuffer); explicit cast: function-style cast
Last edited on
worked perfectly thanks. Stylistically does any one have problems with what I wrote and why? Our hmwk was to code the problem in C and only change the structure to a class.
Topic archived. No new replies allowed.