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

In C++, Write a program to search for a user defined string in a text file and r

ID: 3776400 • Letter: I

Question

In C++,

Write a program to search for a user defined string in a text file and replace it with another user defined string. From your main function, read a text file and ask the user for the string to search and the string to replace with. Write a programmer defined function that accepts a file stream object and two strings, and searches for the first string in the text file. If there is a match, this function will replace the matched string with a second string. Choose any implementation you desire. Use ‘HW6Prob1.txt’ as the input file for this program.

Explanation / Answer


/**
C ++ program that reads a text input.txt
and search for string to replace .
if search string found then replace.
Then rename the file temp as ouptut
and remove the temp file.
*/
//replace.cpp
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//start of main function
int main()
{
   string search = "programming";
   string replace = "coding";  
  
   //open input file for reading
   ifstream filein("HW6Prob1.txt");

   //Create a temporary file
   ofstream fileout("temp.txt");


   //check if files are not opened successfully
   if(!filein || !fileout)
   {
       cout << "File opening error..." << endl;
       return 1;
   }
   string read;
   bool found = false;
   //read file until end of file
   while(filein >> read)
   {
       //check if string is found
       if(read == search)
       {
           read = replace;
           found = true;
       }
       read += " ";
       //write to temp file
       fileout << read;
      
       if(found)
           break;
   }

   //close file streams
   filein.close();
   fileout.close();

   //rename the temp with output.txt
   rename("temp.txt","output.txt");
   //remove temp.txt
   remove("temp.txt");

   //pause program output on console
   system("pause");
   return 0;
}

------------------------------------------------------------------------

HW6Prob1.txt

Welcome to c++ programming

---------------

Output:

output.txt

Welcome to c++ coding