Raman has some data in his laptop saved in two different files, but now he wants to combine the data in one file from these two files. Write a program to complete this task.
The file "Laptop1.txt":
Name: Dell
RAM: 4
HDD: 1
The file "Laptop2.txt":
Graphic card: 2
OS: Windows 10
Processor: Intel i5
C++ code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
const string FILE_NAME_1="Laptop1.txt";
const string FILE_NAME_2="Laptop2.txt";
const string FILE_NAME_3="Laptop3.txt";
//open the file "Laptop1.txt"
ifstream laptop1Ifstream(FILE_NAME_1);
if(!laptop1Ifstream)
{
cerr << "Error: open file '"<<FILE_NAME_1<<"' not found.\n";
return 1;
}
//open the file "Laptop2.txt"
ifstream laptop2Ifstream(FILE_NAME_2);
if(!laptop2Ifstream)
{
cerr << "Error: open file '"<<FILE_NAME_2<<"' not found.\n";
return 1;
}
string name;
string RAM;
string HDD;
//read from the file "Laptop1.txt"
getline(laptop1Ifstream,name);
getline(laptop1Ifstream,RAM);
getline(laptop1Ifstream,HDD);
laptop1Ifstream.close();
cout<<"The file Laptop1.txt information:\n";
cout<<"Name: "<<name<<"\n";
cout<<"RAM: "<<RAM<<"\n";
cout<<"HDD: "<<HDD<<"\n";
string graphicCard;
string OS;
string processor;
//read from the file "Laptop1.txt"
getline(laptop2Ifstream,graphicCard);
getline(laptop2Ifstream,OS);
getline(laptop2Ifstream,processor);
cout<<"\nThe file Laptop2.txt information:\n";
cout<<"Graphic card: "<<graphicCard<<"\n";
cout<<"OS: "<<OS<<"\n";
cout<<"Processor: "<<processor<<"\n\n";
laptop2Ifstream.close();
//Save to the file "Laptop3.txt"
ofstream ofstreamLaptop3(FILE_NAME_3, ios::out);
cout<<"\nThe file Laptop3.txt has been saved.\n";
ofstreamLaptop3<<name<<"\n";
ofstreamLaptop3<<RAM<<"\n";
ofstreamLaptop3<<HDD<<"\n";
ofstreamLaptop3<<graphicCard<<"\n";
ofstreamLaptop3<<OS<<"\n";
ofstreamLaptop3<<processor<<"\n";
ofstreamLaptop3.close();
system("pause");
return 0;
}
Comments
Leave a comment