Jump to content
  • Advertisement
Sign in to follow this  
furiousuk

Saving and Loading strings

This topic is 4481 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm saving to a file called "data.bin" and I'm trying to save a string which contains the name of another file so that when I load the file I can create a texture using the file name to specify the bitmap I want to use. My problem is that I'm getting all sorts of bizarre errors when I save and load strings. I've tried saving and loading the string as LPCTSTR but that won't work. I've tried saving std::strings but I cant load them correctly. I've even tried saving char* but that just flat wont work at all. I've tried using fwrite and fread and also tried using fstream::write and fstream::read. I guess my question is what is the best way of saving and loading strings in C++.

Share this post


Link to post
Share on other sites
Advertisement
What are not working to you get the wrong values?

Your problem is most likely that you do something like this:

std::string out_str = "some string";
std::ofstream out("test.txt");
out << out_str;
out.close();

std::string in_str = "";
std::ifstream in("test.txt");
in >> in_str;
// in_str now equals "some"
in.close();

The problem is that the operator<< outputs the whole string, but the operator>> reads until the next whitespace (' ', '\t', '\n' etc.). If you do something like store one string on each line you can just read the whole line into the str. If you can't ensure that there is only one string on a line then you can prefix every string with the number of characters used and not stop reading until you have read that amount of chars. For example the previous example would output like this:

std::string out_str = "some string";
std::ofstream out("test.txt");
out << out_str.length() << out_str;
out.close();

Now when reading you can start by reading into an int. And then read the string until its length equals the int you just read.

Share this post


Link to post
Share on other sites
Do you want to write the text and with the binary bitmap data?

One possible solution is binary IO.

Kuphryn

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!