Objective: Write a C++ program to demonstrate reading from two files simultaneously.
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// Input file streams for reading data from two files
ifstream inFile1, inFile2;
// Open the first file
inFile1.open("file1.txt");
if (!inFile1) {
cout << "Error opening file1.txt!" << endl;
return 1;
}
// Open the second file
inFile2.open("file2.txt");
if (!inFile2) {
cout << "Error opening file2.txt!" << endl;
inFile1.close(); // Close the first file if the second file fails to open
return 1;
}
// Variables to store lines read from each file
string line1, line2;
// Read from both files simultaneously
while (getline(inFile1, line1) && getline(inFile2, line2)) {
cout << "File1: " << line1 << endl;
cout << "File2: " << line2 << endl;
}
// If one file has more lines, read and display the remaining lines
while (getline(inFile1, line1)) {
cout << "File1: " << line1 << endl;
}
while (getline(inFile2, line2)) {
cout << "File2: " << line2 << endl;
}
// Close the files
inFile1.close();
inFile2.close();
return 0;
}
Output:
No comments:
Post a Comment