Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need help on follwing program using while loop, for c++ langugae. Write a progra

ID: 3678496 • Letter: N

Question

Need help on follwing program using while loop, for c++ langugae.

Write a program that reads two input files whose lines are ordered by a key data field. Your program should merge these two files, writing an output file that contains all lines from both files ordered by the same key field. As an example, if two input files contain student names and grades for a particular class ordered by name, merge the information as shown below.

Using a text editor, create File 1 and File 2. You must read one line of a file at a time and either write it or the last line read from the other data file to the output file. A common merge algorithm is the following:

       Write the line from file 2 to the output file and read
a new line from file 2.
Write the remaining lines (if any) from file 1 to the output file.
Write the remaining lines (if any) from file 2 to the output file.

Explanation / Answer

Program:

#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <string.h>
using namespace std;

int main()
{
   ifstream infile1;
   ifstream infile2;
   ofstream outfile;

   infile1.open("data1.txt");
   if(!infile1)
   {
       cout << "data1.txt file does not exist.";
       return 1;
   }

   infile2.open("data2.txt");
   if(!infile2)
   {
       cout << "data2.txt file does not exist.";
       return 1;
   }

   outfile.open("out.txt");

   string str1;
   string str2;

   getline(infile1, str1);
   getline(infile2, str2);

   while(infile1 && infile2)
   {
       if(strcmp(str1.c_str(), str2.c_str()) < 0)
       {
           outfile << str1 << endl;
           getline(infile1, str1);
       }
       else
       {
           outfile << str2 << endl;
           getline(infile2, str2);
       }
   }

   while(infile1)
   {
       outfile << str1 << endl;
       getline(infile1, str1);
   }

   while(infile2)
   {
       outfile << str2 << endl;
       getline(infile2, str2);
   }

   infile1.close();
   infile2.close();
   outfile.close();

   return 0;
}


Input file: data1.txt

Adams C
Jones D
King B


Input file: data2.txt

Barnes A
Johnson C


Output file: out.txt

Adams C
Barnes A
Johnson C
Jones D
King B

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote