I am confused in the technique used to write string data in binary file. If we write integer data in binary file instead, an example code used is:
1 2
|
int score=55;
myfile.write(reinterpret_cast<char*>(&score),sizeof(score));
|
here we convert the integer variable 'score' to char type and pass the address. but when working with string, why can't we do this:
1 2
|
string name="John Doell";
myfile.write(reinterpret_cast<char*>(&name),sizeof(name));
|
if the answer is regarding size of string, for eg, if you say: "John Doell" has 10 character=10 bytes, which is inconsistent with
sizeof(name)
(second arguement) which is of 4 bytes, so that the only 4 characters of "name" variable i.e. "John", would be written in the binary file. that is why we need to record the length of the string in the actually used method.
But then,regardless, of the length of the string, the variable "name" would still be of 4 bytes, isn't it? as in, here
int a=123456789;
, even if "123456789" has 9 characters=9bytes, while writing into binary file, it somehow manages to write this number in 4 byte variable 'a'. so why can't the same happen while writing string in binary file.
or is this not your answer and i just wasted 2 paragraphs and lot of time describing this. i wrote this because i had been thinking about this approach for quite some time.
if you did not get the above two bulky paragraphy, please ignore it. any help would be appreciated.