Sign in to follow this  
furiousuk

Saving and Loading strings

Recommended Posts

furiousuk    162
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
CTar    1134
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this