Link to home
Start Free TrialLog in
Avatar of claracruz
claracruz

asked on

Wrting int, double, float and char datatypes at the same type.

g'day experts,

I ave a need to write write the folowing data to file. they are in format:

ID- char[20]
name-char[20]
current - unsigned int
usuage - unsigned int
code- char[20]
cost - float.

I a writing to file in the format;

outCustBill.write((char*)(&SaveBill),sizeof(SaveBill));

how do I save all the different datatypes together. Thank you.
Avatar of Member_2_1001466
Member_2_1001466

You can create a struct with these data:

typedef struct Data {
    char[20] ID;
    char[20] name;
    unsigned int current;
    unsigned int usage;
    char[20] code;
    float cost;
} Data_;

Data myData; // and fill the vars.

outCustBill.write (&myData, sizeof (myData));
Avatar of claracruz

ASKER

please explain the use of struct.... thank you
One error correction first: it seems that write needs a char* so cast the first parameter to it
outCustBill.write ((char*) &myData, sizeof (myData));

a struct is a special case class which puts different typed variables into a a single object. Special in the sense that it has public members by default. In this case you collect all the different variables into a single object which can now be written in one go to file (and read back as well). This is also usefull if you need to return different types of variables from a function. An array is not possible since types differ and having all as parameters can harm the legibility of the code.
thank you.

also when you say Data myData; // and fill the vars.

 what exactly does this mean?
The line
Data myData;
creates an object of type Data but all its members have random values yet.

Lines like
strcpy (myData.name, "name1");
myData.current = 13;
myData.cost = 10.5;
do that part and are needed before writing myData to file.
Hi there,

Thanks for all the help... still one more thing though,

I have implemented this and now get error

      ......customer.h(458) : error C2664: 'write' : cannot convert parameter 1 from 'struct Data *' to 'const char *'on line;

              outCustBill.write (&myData, sizeof (myData));

Would you have any ideaof the possible cause of the error.

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Member_2_1001466
Member_2_1001466

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial