Saving and Loading strings

Started by
2 comments, last by kuphryn 18 years, 1 month ago
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++.
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.
Read this.
Do you want to write the text and with the binary bitmap data?

One possible solution is binary IO.

Kuphryn

This topic is closed to new replies.

Advertisement