…as someone may remember, I’m still stuck on C++ strings. Ok, I can write a string to a file using a fstream as follows
outStream.write((char *) s.c_str(), s.size());
When I want to read that string, I can do
inStream.read((char *) s.c_str(), s.size());
Everything works as expected. The problem is: if I change the length of my string after writing it to a file and before reading it again, printing that string won’t bring me back my original string but a shorter/longer one. So: if I have to store many strings on a file, how can I know their size when reading it back?
Thanks a lot!
You shouldn’t be using the unformatted I/O functions (
read()andwrite()) if you just want to write ordinary human-readable string data. Generally you only use those functions when you need to read and write compact binary data, which for a beginner is probably unnecessary. You can write ordinary lines of text instead:Then read them back with
getline():You can also use the regular formatting operator
>>to read, but when applied tostring, it reads tokens (nonwhitespace characters separated by whitespace), not whole lines:All of the formatted I/O functions automatically handle memory management for you, so there is no need to worry about the length of your strings.