outf.write((char*)&book1, sizeof(book1));
|
You are telling your compiler, that the class "Book" should be treates as if it were just a normal sequence of characters.
Book probably looks like this in memory:
- 20 bytes of "title"
- 15 bytes of "author"
- 1 byte padding to reach 4-byte-alignment
- 8 bytes of "price"
- 4 bytes of "quantity"
Except the title and author, they aren't anything like character sequences and even these fields are not completely filled with characters.
But with your outf - line, you are telling the compiler: "shut up, just print the memory-stuff as if it were characters." (The (char*) - thing is the equivalent of "shut up" ;-)
So now it makes sense that you see the garbage output? :)
You most probably do not want to just save the memory state of your book-class unencoded to disk (you will have trouble getting it back later). You may want to save it structured, e.g. line-wise printing out
every member field separately and then read it in like you read from "cin" now.
Ciao, Imi.