storing variables in files

Hello

I have a quite newbie question that I cannot figure out the answer. Let's say that I this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

#include <iostream>
#include<fstream>
using namespace std;

int main(){

int x;
int y;

cout<<"enter a value"<<endl;
cin>>x;

fstream file("data.txt");
file<<x<<endl;

//Now I want to take the value  x and place it to y so if x was
//5 then y will take the value 5 from the file and be equal to it so y=5

...
cout<<y<<endl;

}


Any help appreciated. Thank you in advance
You mean something like this perhaps:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    string fname = "data.txt";
    
    {
        ofstream fout(fname);
        fout << 5 << ' ' << 23 << '\n';
    }
    
    int x, y;
    {
        ifstream fin(fname);
        fin >> x >> y;
    }
    
    cout << "x = " << x << "  y = " << y << '\n';
    
}

Output:
x = 5  y = 23
Thank you for your reply. Can you please explain the lines 11-12 and 17-18?Thank you very much.
He's basically just opening the file(ofstream) "data.txt" and writing to it. Then he Opens the file again(ifstream) to read it, and store the read data in the variable x and y.

http://www.cplusplus.com/doc/tutorial/files/

ofstream fout(fname);
Is the same as
1
2
ofstream myfile;
myfile.open (fname);
Last edited on
OK. I will have to try it to digest it but thanks for the help.
@octopus: try to learn file streaming which is in this web too
Once the fstream (either input or output) is open, then you can use it in exactly the same way as the standard input and output with cin and cout. If you've ever used either of those, then you know how to use files too.

Ok. I tried it a bit but I can't fully understand how the if stream works. Let's say that I have a file.txt with the following:

1
2
3
4
123
654
765
koi


How can I specify where each variable should go and take the value. For instance how can x know that it has to go take the value of the third line. Is it done automatically?
It is done in order.

I'll do some psuedo code -


1
2
3
4
5
int a,b,c;
std::string d;

ifstream file("Text.txt");
file >> a >> b >> c >> d;


After that line, this will be true - a = 123, b = 654, c = 765, d = "koi";


ok thank you. Very clear now. What if the file is like that:

ds ad sr r324 324g sdr 32r

And I want that x=ds, y=ad, z=sr etc.

I see no reason why I would do that but just out of curiosity
Im not sure exactly how the program would react, but it would for sure go completely wrong.

x y and z are integers. ds, ad and sr are definitely not integers. That would be like doing
(I think)
int x = dr;

Why dont you create a text file like that and try it out?
Last edited on
Topic archived. No new replies allowed.