Answer to Question #213959 in C++ for ali

Question #213959

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.



1
Expert's answer
2021-07-07T18:31:27-0400
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);
	
	
}
	




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS