Reading data from an existing file into a string

I open a file and write to it, then close it, then open it again and read it with no problem, I exit my program and then try to read it again and I crash trying to print out title(which is a string), I then changed title to char and it works fine. I'm having a hard time starting my program and reading data from an existing file into a string, char works fine. This is the read and output portion of my code.

void CD_DATABASE :: ShowCdData()
cout << "CD Details are:" << endl;
cout << "Title: " << one_cd.title << endl
<< "Artist: " << one_cd.artist << endl
<< "Tracks: " << one_cd.tracks << endl
<< "Price: " << one_cd.price << endl;

ifstream in(fname, ios::binary);
{*) &sobj.one_cd, sizeof(sobj.one_cd));
cout << "in.close" << endl;
Last edited on
Now, I think I know what is going on. When you open a file for writting, and the structure has some strings in it, because the strings have data it knows the size, so it writes fine. When you close it and open it again for reading it works fine because there is ino on the string size, but when you exit the program all together, and run it again that info on the string size is gone so when you open up the file for reading you get the screen of death. So I'm just using char. Some who knows more please comment.
are you trying to use std::ofstream::write() and std::ifstream::read() to serialize objects of type std::string? It won't work: those functions require trivially-copyable types (such as arrays of char)
Use operator<< and operator>>/std::getline() instead.
Last edited on
That's what I figured. I just changed my string to char, but I'll have to try getline next time.

I'm reading a data structure, that has floats, int, and text, and I had my text as a string, and I just changed it to Char and it worked like a charm.
operator<< and operator>> can handle floats, integers, strings, and more.
Topic archived. No new replies allowed.