How can i save to disk with code? into .txt

It may be strange and hard..i hope someone can help me

i want to save a data from my c++
i want the file save to disk into format .txt then reload the data and open it later but i dont know the code..

so basicly i had data in my code and i want to save it with code into .txt and i can open it later...
hope there is some expert here can help me
It ain't hard at all.
You mean something like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>
#include <string>

    using namespace std;

int main()
{
    const char filename[] = "data.txt";
    
    int i = 123;
    string text = "Hello";

    ofstream outfile(filename);      // open file for writing
    if (outfile) 
    {
        outfile << i << " " << text; // output something
    }
    outfile.close();                 // we finished writing, so close it.
                                     
    i = 0;                           // clear the data, to prove it works
    text = "";

    ifstream  infile(filename);       // open file for reading
    if (infile) 
    {
        infile >> i;                  // read the data from file
        infile >> text;
    }
    infile.close();

    // display the result
    cout << " i: " << i << "  text: " << text << endl;

    return 0;
}
@Chervil


Thanks, but i found that we don't need to use const char instead of char.. i found the code like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>

using namespace std;
int i = 123;
string text = "Heloo";
int main()
{
    char name[100];
    cout<<"Enter the file name [ex = file.txt]: ";
    fflush(stdin);gets(name);
    ofstream outfile(name);      // open file for writing
    if (outfile) 
    {
        outfile << i << " " << text; // output something
    }
    outfile.close();                 // we finished writing, so close it.
                                     
    i = 0;                           // clear the data, to prove it works
    text = "";

    ifstream  infile(name);       // open file for reading
    if (infile) 
    {
        infile >> i;                  // read the data from file
        infile >> text;
    }
    infile.close();

    // display the result
    cout << " i: " << i << "  text: " << text << endl;
    getch();
}

Enter the file name [ex = file.txt]: test.txt
i=123 text=Heloo






but we really thanks..so we could used to it..
Topic archived. No new replies allowed.