Assuming we have following variables and values:
int a=5, b=10, c=15, x, y, z;
Write the values of a, b and c variables in file by using formatted file I/O and then read data accordingly from file and assign it to x, y and z variables. Just create objects of relevant classes, there is no need to write entire main function.
using namespace std;
#include <stdio.h>
/*
Assuming we have following variables and values:
int a=5, b=10, c=15, x, y, z;
Write the values of a, b and c variables in file by using formatted file I/O and
then read data accordingly from file and assign it to x, y and z variables.
Just create objects of relevant classes, there is no need to write entire main function.
*/
main(void)
{
int a=5, b=10, c=15, x, y, z;
fstream textfile;
string file_name = "./Out.txt";
textfile.open(file_name.c_str(), ios::out);
textfile<<a<<"\n"<<b<<"\n"<<c;
textfile.close();
textfile.open(file_name.c_str());
if (!textfile)
{
cout << "Unable to open file: "<<file_name;
exit(1); // terminate with error
}
else
{
b=0;
while(textfile >> a)
{
if(b==0) x = a;
if(b==1) y = a;
if(b==2) z = a;
b++;
}
}
textfile.close();
cout<<"\nData read from the file: "<<file_name;
cout<<"\nx = "<<x;
cout<<"\ny = "<<y;
cout<<"\nz = "<<z;
return(0);
}
Comments
Leave a comment