write the data to text file

how to write and save the data to the text file?
use <fstream> or do you want an example?
can u give me simple example?
Yeah. try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>    //the header file needed for writing to files

using namespace std;

int main()
{
    ofstream myfile("example.txt",ios::out);  //an object of type ostream(for outputting into example.txt)representing
                                        //the file itself in your code. ie,whatever you do to it, will affect the file
    string str;

    cout<<"Enter text to be put in example.txt: ";
    getline(cin,str);  //user inputs into str
    myfile<<str;     //just like using cin or cout, you put what is in str into myfile
    myfile.close();
    cin.get();
    return 0;
}


for more info,
http://cplusplus.com/doc/tutorial/files/
http://cplusplus.com/reference/iostream/
Last edited on
And for reading from a file you would use this:

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

using namespace std;

int main() {
    ifstream myfile( "example.txt", ios::in ); // an object of type istream, used 
                                               // for reading from a file
    string str;

    getline( myfile, str ); // content from file saved in str
    myfile.close(); // close file so it can be used by other applications

    cout << str << endl;

    cin.get();

    return 0;
}
i will try it later.....tq......:)
Topic archived. No new replies allowed.