Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C++
Printing the last item of a structure twice
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Jonathan Lee, post: 3911257"] First I recommend trying this: add the following line before you write to the file: cout << "Writing " << sizeof(ender) << " bytes" << endl; It will print the same thing for every record, on my system that's 8 bytes. It's 8 bytes if I enter a 2 letter string for the street name, and it's 8 bytes if I enter 40 letters for the street name. When it's done, "1.tst" is always 24 bytes. So if I've entered three 40 letter names, how could the data possibly be there? Now to answer your question. What fwrite is doing is writing the 8 bytes (sizeof(ender)) located at the address &meu. Of course, this contains an ender structure, which is roughly struct ender { string rua; int n; } Now rua, the string object, is just a pointer to a char* buffer (a bit of a simplification, but good enough for this discussion). So in reality you have this: struct ender { char* rua; // the only data a string object "contains" int n; } And rua only contains a pointer to the actual string data. So this is what you get when you write it out to the file. As a concrete example, suppose I type in the street name as "ReallyLongStreetName" and the number as 9. When you read the value into rua, it will allocate a char* to hold the data and store that address inside the string object. Let's say that address is 0x40302010. Then 'meu' will hold 0x40302010 // string rua; 0x00000009 // int n; When you write out the file you will get something like 0x40, 0x30, 0x20, 0x10, 0x00, 0x00, 0x00, 0x09 in 1st.tst, which has nothing to do with "ReallyLongStreetName" When you read it back you get the same address back and it just happens to contain the same string, leading you to think that it's working, when it isn't. What you need to do is serialize the object, as I said before. One way to do this would be: write the string length as a number write the C-string value of rua, pointed to by rua.c_str() write the street number One final note: writing numbers is not portable. There is the matter of "endianness", and also sizeof(int). But maybe convince yourself of the above first... --Jonathan [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C++
Printing the last item of a structure twice
Top