Here is data structure with variables:
struct Part_record
{
char id_no[3];
int qoh;
string desc;
double price:
};
---
(Using "cin" to input data)
---
Part_record null_part = {" ", 0," ",0.0};
---
---
file.seekg( -(long)sizeof(Part_record), ios::cur);
file.write( ( char *)&part, sizeof(Part_record) );
The three variables, qoh, Id_no & price, write out correctly, but the "desc" variable is not right. Do I need to initialize Part_record some other way? It should be 20 characters in length.
If you have enough info here, please share your advice.
std::string keeps its data in dynamically allocated memory, not in structure Part_record.
You can't write std::string objects (or any of the STL containers) to a file in this way. They contain internal pointers to their data which is allocated dynamically; you'll wind up writing pointer addresses to your file, instead of the contents of the string.
I'd recommend using the iostream library if you need to write std::string data to a file. Failing that, you can access the character data directly with part.desc[0] to achieve something similar to what you're attempting:
fwrite(&part.desc[0], part.desc.size());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With