Saving Data

Jul 20, 2011 at 4:22pm
Hi, I am a novice and was wondering how I could save data, like a string or integer, to the hard drive to be accessed somehow later on, instead of everything being killed at the end of the program.
Thanks in advance for any help!
Jul 20, 2011 at 4:23pm
By writing them to a file:
http://www.cplusplus.com/doc/tutorial/files/

Look up "serialization" as well.
Jul 20, 2011 at 5:06pm
Thank you!
Jul 20, 2011 at 6:34pm
Hey, how would I go about writing a user's input to a file?

1
2
3
4
5
6
7
  string mystring;
  getline (cin, mystring);

  ofstream myfile;
  myfile.open ("example.txt", ios::app);
  myfile << "Writing here.\n";
  myfile.close();


What would I change?
Jul 20, 2011 at 6:37pm
You'd just change it to myfile << mystring << endl;
Jul 20, 2011 at 6:45pm
I've tried that, and it doesn't seem to be working. Does it work for you?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using namespace std;
#include <iostream>
#include <string>
#include <fstream>

int main ()
{
    string mystring;
    cout << "What do you want to say? ";

        ofstream myfile;
        myfile.open ("conversaton.txt", ios::app);
        
        getline (cin, mystring);
        
        myfile << mystring << endl;
        myfile << "getline(cin, mystring)";
        myfile.close();

	
	return 0;
}
Jul 20, 2011 at 6:51pm
Oh wait, it is working for me; I was looking in the wrong folder. Sorry about that.
Topic archived. No new replies allowed.