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...

  • Write a program that takes in a line of text as input, and outputs that line...

    Write a program that takes in a line of text as input, and outputs that line of text in reverse. You may assume that each line of text will not exceed 50 characters. The program repeats, ending when the user enters "Quit", "quit", or "q" for the line of text. Ex: If the input is: Hello there Hey quit then the output is: ereht olleH уен Hint: Use the fgets function to read a string with spaces from the user...

  • 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...

  • IN C language Write a C program that prompts the user to enter a line of...

    IN C language Write a C program that prompts the user to enter a line of text on the keyboard then echoes the entire line. The program should continue echoing each line until the user responds to the prompt by not entering any text and hitting the return key. Your program should have two functions, writeStr andcreadLn, in addition to the main function. The text string itself should be stored in a char array in main. Both functions should operate...

  • Write a C program that reads characters from a text file, and recognizes the identifiers in...

    Write a C program that reads characters from a text file, and recognizes the identifiers in the text file. It ignores the rest of the characters. An identifier is a sequence of letters, digits, and underscore characters, where the first character is always a letter or an underscore character. Lower and upper case characters can be part of the identifier. The recognized identifier are copied into the output text. b. Change the C program in exercise 2, so that all...

  • Please write a c++ header file, class implementation file and main file that does all of...

    Please write a c++ header file, class implementation file and main file that does all of the following and meets the requirements listed below. Also include a Output of your code as to show that your program works and functions properly. EXERCISING A DOUBLY-LINKED LIST CLASS This project consists of two parts, the second of which appears below. For the first part, write a class that implements an unordered list abstract data type using a doubly-linked list with pointers to...

  • Program In Assembly For this part, your MAL program must be in a file named p5b.mal....

    Program In Assembly For this part, your MAL program must be in a file named p5b.mal. It must have at least one function in addition to the main program. For the purposes of Part (b), you may assume the following 1. Any line of text typed by a user has at most 80 characters including the newline character. 2. A whitespace character refers to a space, a tab or the new line character. 3. A word is any sequence of...

  • 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...

  • Hi everyone, I have a C programming problem, answers are better with explanations. Background Materials: The...

    Hi everyone, I have a C programming problem, answers are better with explanations. Background Materials: The Task: The Answer: The completed C code. Below is the file charIO4C.c: #include <stdio.h> #include <ctype.h> #define QUIT_LETTER 'q' int main(void) { int c, line_length; // Each pass through the outer loop reads a line of input. while (1) { printf("\nEnter a line of text. (To quit, start the line with %c.)\n", QUIT_LETTER); c = fgetc(stdin); if (c == EOF || c == QUIT_LETTER)...

  • //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...

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
ADVERTISEMENT