Hey, I came here to ask for help with my little project, where I need to write to binary file and read from it with other program. I made a simple test programs that does the thing I need - One of them writes a simple struct with 2 member variables (std::string and int), and the second program reads that file, using the same struct. all went well with int type variable, but std::string variable didn`t showed at all or made program crash.
Here is bouth sources of those simple programs:
Writer
ReaderCode:#include <iostream> #include <fstream> #include <string> struct CTest { int number; std::string text; }; int main() { std::ofstream output("level.map", std::ios::binary); CTest obj; obj.number = 255; obj.text = "testing..."; output.write((const char*)(&obj), sizeof(obj)); output.close(); std::cin.get(); return 0; }
What am I doing wrong, and how to write struct with std::string type member correctly? Hope to get some help.Code:#include <iostream> #include <fstream> #include <string> struct CTest { int number; std::string text; }; int main() { std::ifstream input("level.map", std::ios::binary); CTest buffer; input.read((char*)(&buffer), sizeof(buffer)); std::cout << buffer.number << std::endl; std::cout << buffer.text << std::endl; std::cin.get(); return 0; }



LinkBack URL
About LinkBacks


