The homwerok will be graded by computer, so take note one spaces. Q1) Write a C+
ID: 3711914 • Letter: T
Question
The homwerok will be graded by computer, so take note one spaces.
Q1) Write a C++ program that finds all instances of a string in an input text file, replaces them with another string, and writes the result to an output file. At the start of the program prompt the user to input the string that they want to find by printing "Find: " and read the input string. Then, prompt the user to input the replacement string by printing "Replace with: n" and read the input string. The following input/output pairs assume that the input text file reads as follows: "In C and C++, problems may be faced if two (or more) include files both in turn include the same third file." (a) Find: include Replace with: EXCLUDE Resulting output file: "In C and C++, problems may be faced if two (or more) EXCLUDE files both in turn EXCLUDE the same third file." b) Find: C++ Replace with: LANGUAGE Resulting output file"In C and C++, problems may be faced if two (or more) include files both in turn include the same third file." (c) Find: C++, Replace with: LANGUAGE Resulting output file: "In C and LANGUAGE problems may be faced if two (or more) include files both in turn include the same third file." Note: You must write your code in a source file named find replace.cpp. In your code, you must read from a text file named text in.txt and write to a text file named text out.txt You are provided an example input text file to test your code. Use the string type that is accessible when you includeExplanation / Answer
Solution:
code:
#include<fstream>
#include<conio.h>
#include<string.h>
void main()
{
//create object to open a file to read data from a file
ifstream filein("text_in.txt");
//create object to which string is to be written
fstream filout("text_out.txt", fstream::out);
char Find[50], Replace[50], text[50];
if(!filein)
cout<<" File cannot be opened"<<endl;
else
{
cout<<" Find: ";
cin>>Find;
cout<<"Replace: ";
cin>>Replace;
while(!filein.eof())
{
filein.getline(text, 50, ' '); //read the input file
if(strcmp(text, Find)==0) //compare the input form file with the user entered string
strcpy(text, Replace); //replace the string
strcat(text, " "); //write to the file
filout<<text;
}
}
//close the objects
filout.close();
filein.close();
//open the file text_out.txt in read mode to now read data from it
ifstream filin("text_out.txt");
if(!filin)
cout<<" Unable to open file";
else{
cout<<" resulting Output File: "<<endl;
while(!filin.eof())
{
filin.getline(text, 50, ' ');
cout<<text<<" ";
}
cout<<endl;
}
filin.close();
getch();
}
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.