Question

Write a c++ program in that file to perform a “Search and Replace All” operation. This...

Write a c++ program in that file to perform a “Search and Replace All” operation. This operation consists of performing a case-sensitive search for all occurrences of an arbitrary sequence of characters within a file and substituting another arbitrary sequence in place of them. Please note: One of the biggest problems some students have with this exercise occurs simply because they don’t read the command line information in the course document titled “Using the Compiler’s IDE”. Your program:

1. must check the success/failure status of opening any file immediately after opening it;

2. may assume, for simplicity, that it will only be used with text files;

3. may assume, for simplicity, that the input and output file names will be different;

4. may assume, for simplicity, that no character sequence will be split across multiple lines;

5. must support multiple occurrences of a character sequence on a single line;

6. must support cases where the length of the “search” character sequence is different from the length of the “replacement” character sequence;

7. must get the following information from the command line (spaces must be allowed in all items): a. the name of the file to search; b. the name of the file to store the results in; c. the sequence of characters to search for; d. the sequence of characters to use as replacements;

8. must verify that exactly the correct number of command arguments are present and exit with an error message and error code if not;

9. must not access any command arguments before verifying that they actually exist;

10. must not use data types list, queue, stack, string, or vector.

11. must not call the strlen more than once for the same string, including placing such a call inside a loop. I recommend reading the file one line at a time and parsing it with the standard strstr library function to find each search sequence, then using the following 4-step algorithm to process each sequence:

1. Copy from the old file into the new file up to where a “search” sequence starts;

2. Copy the “substitution” sequence into the new file;

3. Skip the “search” sequence in the old file;

4. Repeat steps 1-3 until EOF is reached. Manually re-run your program several times, testing at least the following 2 cases with instructor-supplied data file TestFile1.txt.

Choose any name you wish for the output file as long as it is different from the input file name:

For example (Test #1), if the input file contained, These are the answers to neither of their questions! the output file would contain, These are Who is John Galt? answers to neiWho is John Galt?r of Who is John Galt?ir questions!

Note that there were three replacements on one line and that “the” was part of another word in two of those cases. Hints: EOF cannot be correctly stored or detected using data type char or unsigned char; use type int instead 6 (Notes 4.3A & 4.3B).

Since EOF only occurs when a read (or write) is attempted, testing for it before such an attempt is meaningless and wrong. Only test after such an attempt before the value obtained from reading is actually used (Note 4.3B).

Below is a description of the step-by-step algorithm I used to implement the “Search and Replace All” requirements of this exercise. I make no claim that this is the best approach and you may feel free to either use it or implement your own. Regardless of what you implement, make sure you understand exactly what it does. Drawing a diagram of memory as the algorithm progresses always helps. The basic concept of the algorithm is that for each line in the input file, do the following:

1. Set a pointer to the first character in the input line.

2. Copy characters into the output file from the pointer to where the string to be replaced starts.

3. Write the replacement string into the output file.

4. Move the pointer to the next character in the input line after the string to be replaced.

5. Repeat steps 2 through 4 until the end of the line has been reached. These are the implementation specifics for the algorithm above:

1. Do all the standard things, including declaring needed variables and opening the input and output files.

2. Implement a loop statement that contains the following 3 statements (a, b, and c) in order: a. a statement that gets the next line from the input file and stores it into a character buffer. (The newline character must be discarded.)

If the EOF condition occurs, terminate the loop. Otherwise, proceed to step b below. b. a “for” statement that does everything in steps i and ii below (in order): i. does the following in its “control” section. The “control” section is the portion of the “for” statement that is in parentheses just after the keyword for:

1) The “initial expression” initializes a character pointer (I’ll call it cp1) to point to the beginning of the character buffer you are reading each line into.

2) The “controlling expression” assigns the return value of the strstr function to a different character pointer (I’ll call it cp2). The first argument of strstr will be cp1 and the second argument will be a pointer to the first character of the string you are looking for in the file.

3) The “loop expression” is empty. ii. does the following in the loop “body”:

1) Uses the write function to write to the output file. The first argument of write will be cp1 and the second will be cp2-cp1.

2) Writes the replacement string to the output file.

3) Updates cp1 by assigning to it the sum of cp2 and the length of the string 46 you are searching for in the file. c. a statement that writes the string in cp1 and a newline character to the output file. SAVE BELOW AS:

FileText1.txt The number-sign or "stringizing" operator (#) converts macro parameters (after expansion) to string constants. It is used only with macros that take arguments. If it precedes a formal parameter in the macro definition, the actual argument passed by the macro invocation is enclosed in quotation marks and treated as a string literal. The string literal then replaces each occurrence of a combination of the stringizing operator and formal parameter within the macro definition. White space preceding the first token of the actual argument and following the last token of the actual argument is ignored. Any white space between the tokens in the actual argument is reduced to a single white space in the resulting string literal. Thus, if a comment occurs between two tokens in the actual argument, it is reduced to a single white space. The resulting string literal is automatically concatenated with any adjacent string literals from which it is separated only by white space.

Manually re-run your program several times, testing at least the following 2 cases with instructor-supplied data file TestFile1.txt, which must be placed in the program’s “working directory”. For example (Test #1), if the input file contained, These are the answers to neither of their questions! the output file would contain, These are John Galt? answers to neiJohn Galt?r of John Galt?ir questions! Note that there were three replacements on one line and that “the” was part of another word in two of those cases.

Hints:
The value of EOF cannot be correctly stored or detected using data type char or unsigned char;
use type int instead (Notes 4.3A & 4.3B). Since EOF only occurs when a read (or write) is
attempted, testing for it before such an attempt is meaningless and inappropriate. Only test
after such an attempt before the value obtained from reading is actually used (Note 4.3B).
Not testing files for a successful opening is bad programming (Notes 10.3 & 10.4B).
It is not necessary to determine the length of the replacement string.


You may use any algorithm you wish to complete this exercise as long as none of the  requirements/restrictions are violated. The following describes the algorithm I used and recommend.
Drawing a diagram of memory as the algorithm progresses always helps:

General Algorithm Description:
For each line in the input file
{
Set a pointer to first character in line;
For each “search” sequence found in line using the strstr library function
{
Copy characters into the output file from the pointer to where the “search” sequence starts;
Write the replacement string into the output file;
Move the pointer to the next character in the input line after the “search” sequence ends;
}
Copy remainder of line into the output file;
}

Algorithm Step-by-Step Implementation Details:
1. Do all the standard things, including declaring needed variables and opening the input and
output files.
2. Implement a loop statement that contains the following 3 statements (a, b, and c) in order:
a. a statement that gets the next line from the input file and stores it into a character buffer.
(The newline character must be discarded.) If the EOF condition occurs, terminate the
loop. Otherwise, proceed to step b below.
b. a “for” statement that does everything in steps i and ii below (in order):
i. does the following in its “control” section. The “control” section is the portion of
the “for” statement that is in parentheses just after the keyword for:
1) The “initial expression” (Note 3.5) initializes a character pointer (I’ll call it
cp1) to point to the beginning of the character buffer you are reading
each line into.
43 2) The “controlling expression” (Note 3.5) assigns the return value of the
44 strstr function to a different character pointer (I’ll call it cp2). The first
45 argument of strstr will be cp1 and the second argument will be a
46 pointer to the first character of the string you are looking for in the file.
47 3) The “loop expression” (Note 3.5) is empty.
48 ii. does the following in the loop “body”:
49 1) Uses the write function to write to the output file. The first argument of
50 write will be cp1 and the second will be cp2-cp1.
51 2) Uses the << operator to write the replacement string to the output file.
52 3) Updates cp1 by assigning to it the sum of cp2 and the length of the string
53 you are searching for in the file.
54 c. a statement that writes the string in cp1 and a newline character to the output file.

Code is enough than diagram

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include<iostream.h>

#include<conio.h>

#include<string.h>

#include<fstream.h>

using namespace std;

void main(){

fstream i,o,t;              //file for input, output and temporary respectively

char *c1;                   //pointer addressing current character position

string search,replace;

i.open("input.txt");            //initializing the file

o.open("output.txt");

t.open("temp.txt");

if ((i.open&&o.open)&&t.open())          //checking if file accessible

   cout<<"file open successfully";

else

   cout<<"Error opening file";

   getch();

   exit(1);

int count=0;

while(getline(i,t))                   //loop along each line

   count++;

   int store[count][100];           //array of length total number of lines and width of 100 to store pointer value

while(!i.eof())                          //loop till end of file and copy each character from input file to temporary file

   i.get(&c1);

   t<<&c1;

   c1++;

cout<<"enter the search phrase";        //start searching code

cin>>search;

cout<<"enter replace phrase";

cin>>replace;

bool found=0;

while(!i.eof())

int l;

getline(i.t); //read each line from input and store to tmp

for(int i=0;i<search.size();i++)          //linewise iteration

    if(t[i]==search[i])           //case sensitive comparison

    found=1;

    l++;

if(found)

    for(int i=search.size()+1;i<t[i].size(),i++)     //iteration of characters on single line

        store[l][i]=1;

for(i=0;i<count;i++)                      //start replacing code

   for(j=0;j<100,j++)

      if(store[i][j]=1)                      //from array access positions where search phrase found

         o.replace(&c1,search.size(),replace);        //replace from position to size of phrase with

         o<<&c1;

         c1++;

while(!t.eof())                              //copy from the temporary file and write to the output file

   t.get(&c1);

   o<<&c1;

   c1++;

getch();

return(0);

}

        

Add a comment
Know the answer?
Add Answer to:
Write a c++ program in that file to perform a “Search and Replace All” operation. This...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • A. File I/O using C library functions File I/O in C is achieved using a file...

    A. File I/O using C library functions File I/O in C is achieved using a file pointer to access or modify files. Processing files in C is a four-step process: o Declare a file pointer. o Open the desired file using the pointer. o Read from or write to the file and finally, o Close the file. FILE is a structure defined in <stdio.h>. Files can be opened using the fopen() function. This function takes two arguments, the filename and...

  • FOR JAVA Write a program that takes two command line arguments: an input file and an...

    FOR JAVA Write a program that takes two command line arguments: an input file and an output file. The program should read the input file and replace the last letter of each word with a * character and write the result to the output file. The program should maintain the input file's line separators. The program should catch all possible checked exceptions and display an informative message. Notes: This program can be written in a single main method Remember that...

  • Write a program **(IN C)** that displays all the phone numbers in a file that match the area code...

    Write a program **(IN C)** that displays all the phone numbers in a file that match the area code that the user is searching for. The program prompts the user to enter the phone number and the name of a file. The program writes the matching phone numbers to the output file. For example, Enter the file name: phone_numbers.txt Enter the area code: 813 Output: encoded words are written to file: 813_phone_numbers.txt The program reads the content of the file...

  • Write a C program named space_to_line.c that features a while loop that continuously reads input from...

    Write a C program named space_to_line.c that features a while loop that continuously reads input from the user one character at a time and then prints that character out. The exception is that if the user inputs a space character (‘ ‘), then a newline character (‘\n’) should be printed instead. This will format the output such that every word the user inputs is on its own line. Other than changing the spaces to newlines, the output should exactly match...

  • C++ not C please Lyric Search Write a program that asks the user for a file...

    C++ not C please Lyric Search Write a program that asks the user for a file name and a string to search for. The program should search the file for every occurrance of the string. When the string is found it should display the line that it iwas found on and report the total number of occurrances of the string at the end. Place a text file with your favorite song lyrics in it and use to to perform a...

  • Write a program in C that takes a file name as the only argument on the...

    Write a program in C that takes a file name as the only argument on the command line, and prints out the number of 0-bits and 1-bits in the file int main ( int argc , char * argv [] ) { // Check if the user gave an argument , otherwise print " ERROR : no argument " // Check if the file can be read , otherwise print " ERROR : can ’t read " // Otherwise ,...

  • //I NEED THE PROGRAM IN C LANGUAGE!// QUESTION: I need you to write a program which...

    //I NEED THE PROGRAM IN C LANGUAGE!// QUESTION: I need you to write a program which manipulates text from an input file using the string library. Your program will accept command line arguments for the input and output file names as well as a list of blacklisted words. There are two major features in this programming: 1. Given an input file with text and a list of words, find and replace every use of these blacklisted words with the string...

  • Overview: file you have to complete is WordTree.h, WordTree.cpp, main.cpp Write a program in C++ that...

    Overview: file you have to complete is WordTree.h, WordTree.cpp, main.cpp Write a program in C++ that reads an input text file and counts the occurrence of individual words in the file. You will see a binary tree to keep track of words and their counts. Project description: The program should open and read an input file (named input.txt) in turn, and build a binary search tree of the words and their counts. The words will be stored in alphabetical order...

  • //Done in C please! //Any help appreciated! Write two programs to write and read from file...

    //Done in C please! //Any help appreciated! Write two programs to write and read from file the age and first and last names of people. The programs should work as follows: 1. The first program reads strings containing first and last names and saves them in a text file (this should be done with the fprintf function). The program should take the name of the file as a command line argument. The loop ends when the user enters 0, the...

  • Program Description: (C++). Write a word search program that searches an input data file for a...

    Program Description: (C++). Write a word search program that searches an input data file for a word specified by the user. The program should display the number of times the word appears in the input data file. In addition, the program should count and display the number of characters in the input data file that are not vowels. Your program must do this by providing the following functions : void processFile(ifstream &inFile, string &word, int &wordCount, int &nonVowelCount) ; void...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT