#include <iostream>
#include<fstream>
usingnamespace 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;
}
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.
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?