SlideShare a Scribd company logo
Write a C++ program
1. Study the function process_text() in file "text_processing.cpp". What do the string member
functions find(), substr(), c_str() do?
//text_processing.cpp
#include "util.h"
#include "text_processing.h"
#include
using namespace std;
int process_text( fstream &ifs, fstream &ofs, char target[] )
{
string replace_str( "XXX" ); //hard-coded string for replacement
int tlen = strlen( target ); //string length of target
int max_len = 200; //maximum length of a line
char s[max_len+1];
clear_screen(); //clear the screen
while ( !ifs.eof() ) {
int i2, i1 = 0, len=0;
ifs.getline( s, max_len ); //get one line from file
string str( s ); //construct a string object
i2 = str.find ( target, i1 ); //find target
len = i2 - i1;
if ( i2 > -1 && len > 0 ){ //if target found
print_text( str.substr( i1, i2 ).c_str() ); //print up to target
ofs << str.substr( i1, i2 );
}
while ( i2 > -1 ) {
print_text_inverse ( target ); //highlight target
ofs << replace_str;
i1 = i2 + tlen; //new search position
i2 = str.find ( target, i1 ); //find next target
len = i2 - i1;
if ( i2 > -1 && len > 0 ){ //found target
print_text( str.substr( i1, len ).c_str() ); //print up to target
ofs << str.substr( i1, len );
}
}
len = str.length() - i1;
if ( len > 0 ) { //print the remainder
print_text( str.substr( i1, len ).c_str() );
ofs << str.substr( i1, len );
}
ofs << endl;
getnstr( s, 1 ); //prompt for
} //while ( !ifs.eof() )
restore_screen(); //restore the old screen
return 1;
}
//text_processing.h
#ifndef TEXT_PROCESSING_H
#define TEXT_PROCESSING_H
#include
#include
using namespace std;
int process_text( fstream &ifs, fstream &ofs, char target[] );
#endif
//util.h
#ifndef UTIL_H
#define UTIL_H
#include
#include
#include
#include
#include
using namespace std;
void usage ( char program_name[] );
void clear_screen();
void print_text( const char *s );
void print_text_inverse( const char *s );
void get_input_text( char *s, int max_len );
void restore_screen();
#endif
//util.cpp
#include "util.h"
void usage ( char program_name[] )
{
cout << "Usage: " << program_name << " infile outfile search_string" << endl;
return;
}
/*
The following are some curses functions. You can find
the details by the command "man ncurses". But its use
can be transparent to you.
*/
void clear_screen()
{
initscr();
scrollok ( stdscr, true ); //allow window to scroll
}
void print_text ( const char *s )
{
printw("%s", s );
refresh();
}
void print_text_inverse( const char *s )
{
attron( A_REVERSE );
printw("%s", s );
attroff( A_REVERSE );
refresh();
}
void get_input_text( char *s, int max_len )
{
getnstr( s, max_len );
}
void restore_screen()
{
endwin();
}
//str_main.cpp
#include "util.h"
#include "text_processing.h"
#include
using namespace std;
/*
Note that grace_open() must be defined in same file
as main(), otherwise the destructor of fstream will
automatically close the opened file as it finds that
its out of scope upon exiting the function.
*/
int grace_open( char *s, fstream &fs, char *mode )
{
if ( mode == "in" )
fs.open ( s, ios::in );
else if ( mode == "out" )
fs.open ( s, ios::out );
if ( fs.fail() ) {
cout << "error opening file " << s << endl;
return -1;
} else
return 1;
} //grace_open
int main( int argc, char *argv[] )
{
const int max_len = 200;
char s[max_len+1];
char target[100];
if ( argc < 4 ) {
usage( argv[0] );
return 1;
}
char *pin = argv[1]; //pointing to input filename
char *pout = argv[2]; //pointing to output filename
strcpy ( target, argv[3] ); //target for search
fstream ifs, ofs; //input output filestream
if ( grace_open ( pin, ifs, "in" ) < 0 )
return 1; //fail
if ( grace_open ( pout, ofs, "out" ) < 0 )
return 1; //fail
process_text( ifs, ofs, target );
return 0;
}
2. Modify ( or write your own ) the program so that it does the following.
1. It displays a detailed help menu when one executes
find_pat --help
2. It asks for an additional input argument, "replacing string" in addition to the three
arguments described above. Namely, the four input arguments are: input filename, output
filename, target string, replacing string. Instead of replacing the target strings by "XXX",
replace them by the replacing string in the output file. For example
find_pat text_processing.cpp out.txt in abc
will replace all "in" by "abc" in "out.txt".
3. Highlight the "replacing string" on the screen instead of the "target string". ( Do not need
to display the "target string" any more. )
Solution
1. int find(const string & s, int pos = 0) it searches the invoking string forsstarting at indexposand
returns the index wheresis first located.
substr() return a substring from the invoking string.
c_str() it converts string to c styled string. it returns a const char* that points to a null-terminated
c styled basic string.
2.
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
void usage ( char program_name[] )
{
cout << "Usage: " << program_name << " infile outfile search_string replaced_string" <<
endl;
return;
}
void clear_screen()
{
initscr();
scrollok ( stdscr, true ); //allow window to scroll
}
void print_text ( const char *s )
{
printw("%s", s );
refresh();
}
void print_text_inverse( const char *s )
{
attron( A_REVERSE );
printw("%s", s );
attroff( A_REVERSE );
refresh();
}
void get_input_text( char *s, int max_len )
{
getnstr( s, max_len );
}
void restore_screen()
{
endwin();
}
int process_text( fstream &ifs, fstream &ofs, char target[], char rep_str[] )
{
string replace_str( rep_str ); //hard-coded string for replacement
int tlen = strlen( target ); //string length of target
int max_len = 200; //maximum length of a line
char s[max_len+1];
clear_screen(); //clear the screen
while ( !ifs.eof() ) {
int i2, i1 = 0, len=0;
ifs.getline( s, max_len ); //get one line from file
string str( s ); //construct a string object
i2 = str.find ( target, i1 ); //find target
len = i2 - i1;
if ( i2 > -1 && len > 0 ){ //if target found
print_text( str.substr( i1, i2 ).c_str() ); //print up to target
ofs << str.substr( i1, i2 );
}
while ( i2 > -1 ) {
print_text_inverse ( rep_str ); //highlight target
ofs << replace_str;
i1 = i2 + tlen; //new search position
i2 = str.find ( target, i1 ); //find next target
len = i2 - i1;
if ( i2 > -1 && len > 0 ){ //found target
print_text( str.substr( i1, len ).c_str() ); //print up to target
ofs << str.substr( i1, len );
}
}
len = str.length() - i1;
if ( len > 0 ) { //print the remainder
print_text( str.substr( i1, len ).c_str() );
ofs << str.substr( i1, len );
}
ofs << endl;
getnstr( s, 1 ); //prompt for
} //while ( !ifs.eof() )
restore_screen(); //restore the old screen
return 1;
}
int grace_open( char *s, fstream &fs, char *mode )
{
if ( mode == "in" )
fs.open ( s, ios::in );
else if ( mode == "out" )
fs.open ( s, ios::out );
if ( fs.fail() ) {
cout << "error opening file " << s << endl;
return -1;
} else
return 1;
} //grace_open
int main( int argc, char *argv[] )
{
const int max_len = 2000;
char s[max_len+1];
char target[100];
char replace[100];
if ( argc < 5 ) {
usage( argv[0] );
return 1;
}
char *pin = argv[1]; //pointing to input filename
char *pout = argv[2]; //pointing to output filename
strcpy ( target, argv[3] ); //target for search
strcpy ( replace, argv[4] ); //target for search
fstream ifs, ofs; //input output filestream
if ( grace_open ( pin, ifs, "in" ) < 0 )
return 1; //fail
if ( grace_open ( pout, ofs, "out" ) < 0 )
return 1; //fail
process_text( ifs, ofs, target, replace );
return 0;
}

More Related Content

Similar to Write a C++ program 1. Study the function process_text() in file.pdf

Data structures
Data structuresData structures
Data structures
gayatrigayu1
 
C Exam Help
C Exam Help C Exam Help
C Exam Help
Programming Exam Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
Programming Homework Help
 
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
Abdulrahman890100
 
IN C++ languageWrite a simple word processor that will accept text.pdf
IN C++ languageWrite a simple word processor that will accept text.pdfIN C++ languageWrite a simple word processor that will accept text.pdf
IN C++ languageWrite a simple word processor that will accept text.pdf
aratextails30
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in cgkgaur1987
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptxObject Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
C q 3
C q 3C q 3
array, function, pointer, pattern matching
array, function, pointer, pattern matchingarray, function, pointer, pattern matching
array, function, pointer, pattern matching
Shakila Mahjabin
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
arshiartpalace
 
Shell to be modified#include stdlib.h #include unistd.h .pdf
Shell to be modified#include stdlib.h #include unistd.h .pdfShell to be modified#include stdlib.h #include unistd.h .pdf
Shell to be modified#include stdlib.h #include unistd.h .pdf
clarityvision
 
C Programming Project
C Programming ProjectC Programming Project
C Programming Project
Vijayananda Mohire
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdfCan anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
arjunhassan8
 
streams and files
 streams and files streams and files
streams and files
Mariam Butt
 

Similar to Write a C++ program 1. Study the function process_text() in file.pdf (20)

Data structures
Data structuresData structures
Data structures
 
C Exam Help
C Exam Help C Exam Help
C Exam Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
IN C++ languageWrite a simple word processor that will accept text.pdf
IN C++ languageWrite a simple word processor that will accept text.pdfIN C++ languageWrite a simple word processor that will accept text.pdf
IN C++ languageWrite a simple word processor that will accept text.pdf
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
 
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptxObject Oriented Programming Using C++: Ch12 Streams and Files.pptx
Object Oriented Programming Using C++: Ch12 Streams and Files.pptx
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
String Manipulation Function and Header File Functions
 
C q 3
C q 3C q 3
C q 3
 
array, function, pointer, pattern matching
array, function, pointer, pattern matchingarray, function, pointer, pattern matching
array, function, pointer, pattern matching
 
Sbaw091006
Sbaw091006Sbaw091006
Sbaw091006
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
Shell to be modified#include stdlib.h #include unistd.h .pdf
Shell to be modified#include stdlib.h #include unistd.h .pdfShell to be modified#include stdlib.h #include unistd.h .pdf
Shell to be modified#include stdlib.h #include unistd.h .pdf
 
C Programming Project
C Programming ProjectC Programming Project
C Programming Project
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdfCan anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
Can anyone fix this code, I use Visual StudiosThe Errors im getti.pdf
 
streams and files
 streams and files streams and files
streams and files
 

More from jillisacebi75827

Project Communications Management Case StudySeveral issues have a.pdf
Project Communications Management Case StudySeveral issues have a.pdfProject Communications Management Case StudySeveral issues have a.pdf
Project Communications Management Case StudySeveral issues have a.pdf
jillisacebi75827
 
Priority encoders are much more common than non-priority encoders. W.pdf
Priority encoders are much more common than non-priority encoders. W.pdfPriority encoders are much more common than non-priority encoders. W.pdf
Priority encoders are much more common than non-priority encoders. W.pdf
jillisacebi75827
 
Prove that a reversible adiabatic process cannot also be isothermal f.pdf
Prove that a reversible adiabatic process cannot also be isothermal f.pdfProve that a reversible adiabatic process cannot also be isothermal f.pdf
Prove that a reversible adiabatic process cannot also be isothermal f.pdf
jillisacebi75827
 
Passing arguments by-Value and using return types.#includeiost.pdf
Passing arguments by-Value and using return types.#includeiost.pdfPassing arguments by-Value and using return types.#includeiost.pdf
Passing arguments by-Value and using return types.#includeiost.pdf
jillisacebi75827
 
Organophosphates area. herbicidesb. insecticidesDithiocarbama.pdf
Organophosphates area. herbicidesb. insecticidesDithiocarbama.pdfOrganophosphates area. herbicidesb. insecticidesDithiocarbama.pdf
Organophosphates area. herbicidesb. insecticidesDithiocarbama.pdf
jillisacebi75827
 
Match the functions with the plots. The following pictures are image.pdf
Match the functions with the plots. The following pictures are image.pdfMatch the functions with the plots. The following pictures are image.pdf
Match the functions with the plots. The following pictures are image.pdf
jillisacebi75827
 
July 4 Paid utilities expense of $370 Cash Accounts Payable Service .pdf
July 4 Paid utilities expense of $370 Cash Accounts Payable Service .pdfJuly 4 Paid utilities expense of $370 Cash Accounts Payable Service .pdf
July 4 Paid utilities expense of $370 Cash Accounts Payable Service .pdf
jillisacebi75827
 
Income statements and balance sheets follow for The New York Times C.pdf
Income statements and balance sheets follow for The New York Times C.pdfIncome statements and balance sheets follow for The New York Times C.pdf
Income statements and balance sheets follow for The New York Times C.pdf
jillisacebi75827
 
How do contemporary economic geographers view the economy From a ge.pdf
How do contemporary economic geographers view the economy From a ge.pdfHow do contemporary economic geographers view the economy From a ge.pdf
How do contemporary economic geographers view the economy From a ge.pdf
jillisacebi75827
 
I am solving Rational Inequalities and I am a little confused about .pdf
I am solving Rational Inequalities and I am a little confused about .pdfI am solving Rational Inequalities and I am a little confused about .pdf
I am solving Rational Inequalities and I am a little confused about .pdf
jillisacebi75827
 
How would your plates appear if you incubated agar when they were co.pdf
How would your plates appear if you incubated agar when they were co.pdfHow would your plates appear if you incubated agar when they were co.pdf
How would your plates appear if you incubated agar when they were co.pdf
jillisacebi75827
 
Hormones are distributed throughout the body in blood and other body.pdf
Hormones are distributed throughout the body in blood and other body.pdfHormones are distributed throughout the body in blood and other body.pdf
Hormones are distributed throughout the body in blood and other body.pdf
jillisacebi75827
 
Explain the internet infrastructure stack. SolutionInternet inf.pdf
Explain the internet infrastructure stack. SolutionInternet inf.pdfExplain the internet infrastructure stack. SolutionInternet inf.pdf
Explain the internet infrastructure stack. SolutionInternet inf.pdf
jillisacebi75827
 
Each hormone is known to have a specific target tissue. For each of t.pdf
Each hormone is known to have a specific target tissue. For each of t.pdfEach hormone is known to have a specific target tissue. For each of t.pdf
Each hormone is known to have a specific target tissue. For each of t.pdf
jillisacebi75827
 
Describe the differences in the appearance of the sterile tube of Try.pdf
Describe the differences in the appearance of the sterile tube of Try.pdfDescribe the differences in the appearance of the sterile tube of Try.pdf
Describe the differences in the appearance of the sterile tube of Try.pdf
jillisacebi75827
 
As we entered the 21st century, the Human Genome Project, a massive .pdf
As we entered the 21st century, the Human Genome Project, a massive .pdfAs we entered the 21st century, the Human Genome Project, a massive .pdf
As we entered the 21st century, the Human Genome Project, a massive .pdf
jillisacebi75827
 
ActiveX is used by which of the following technologiesA. JavaB..pdf
ActiveX is used by which of the following technologiesA. JavaB..pdfActiveX is used by which of the following technologiesA. JavaB..pdf
ActiveX is used by which of the following technologiesA. JavaB..pdf
jillisacebi75827
 
CBE 20. The following information is from financial statements (in mi.pdf
CBE 20. The following information is from financial statements (in mi.pdfCBE 20. The following information is from financial statements (in mi.pdf
CBE 20. The following information is from financial statements (in mi.pdf
jillisacebi75827
 
Below is a simple Role Play Game (RPG) Simulator program.importjav.pdf
Below is a simple Role Play Game (RPG) Simulator program.importjav.pdfBelow is a simple Role Play Game (RPG) Simulator program.importjav.pdf
Below is a simple Role Play Game (RPG) Simulator program.importjav.pdf
jillisacebi75827
 
A swim bladder allows a fish to Regulate its water content in sea wa.pdf
A swim bladder allows a fish to  Regulate its water content in sea wa.pdfA swim bladder allows a fish to  Regulate its water content in sea wa.pdf
A swim bladder allows a fish to Regulate its water content in sea wa.pdf
jillisacebi75827
 

More from jillisacebi75827 (20)

Project Communications Management Case StudySeveral issues have a.pdf
Project Communications Management Case StudySeveral issues have a.pdfProject Communications Management Case StudySeveral issues have a.pdf
Project Communications Management Case StudySeveral issues have a.pdf
 
Priority encoders are much more common than non-priority encoders. W.pdf
Priority encoders are much more common than non-priority encoders. W.pdfPriority encoders are much more common than non-priority encoders. W.pdf
Priority encoders are much more common than non-priority encoders. W.pdf
 
Prove that a reversible adiabatic process cannot also be isothermal f.pdf
Prove that a reversible adiabatic process cannot also be isothermal f.pdfProve that a reversible adiabatic process cannot also be isothermal f.pdf
Prove that a reversible adiabatic process cannot also be isothermal f.pdf
 
Passing arguments by-Value and using return types.#includeiost.pdf
Passing arguments by-Value and using return types.#includeiost.pdfPassing arguments by-Value and using return types.#includeiost.pdf
Passing arguments by-Value and using return types.#includeiost.pdf
 
Organophosphates area. herbicidesb. insecticidesDithiocarbama.pdf
Organophosphates area. herbicidesb. insecticidesDithiocarbama.pdfOrganophosphates area. herbicidesb. insecticidesDithiocarbama.pdf
Organophosphates area. herbicidesb. insecticidesDithiocarbama.pdf
 
Match the functions with the plots. The following pictures are image.pdf
Match the functions with the plots. The following pictures are image.pdfMatch the functions with the plots. The following pictures are image.pdf
Match the functions with the plots. The following pictures are image.pdf
 
July 4 Paid utilities expense of $370 Cash Accounts Payable Service .pdf
July 4 Paid utilities expense of $370 Cash Accounts Payable Service .pdfJuly 4 Paid utilities expense of $370 Cash Accounts Payable Service .pdf
July 4 Paid utilities expense of $370 Cash Accounts Payable Service .pdf
 
Income statements and balance sheets follow for The New York Times C.pdf
Income statements and balance sheets follow for The New York Times C.pdfIncome statements and balance sheets follow for The New York Times C.pdf
Income statements and balance sheets follow for The New York Times C.pdf
 
How do contemporary economic geographers view the economy From a ge.pdf
How do contemporary economic geographers view the economy From a ge.pdfHow do contemporary economic geographers view the economy From a ge.pdf
How do contemporary economic geographers view the economy From a ge.pdf
 
I am solving Rational Inequalities and I am a little confused about .pdf
I am solving Rational Inequalities and I am a little confused about .pdfI am solving Rational Inequalities and I am a little confused about .pdf
I am solving Rational Inequalities and I am a little confused about .pdf
 
How would your plates appear if you incubated agar when they were co.pdf
How would your plates appear if you incubated agar when they were co.pdfHow would your plates appear if you incubated agar when they were co.pdf
How would your plates appear if you incubated agar when they were co.pdf
 
Hormones are distributed throughout the body in blood and other body.pdf
Hormones are distributed throughout the body in blood and other body.pdfHormones are distributed throughout the body in blood and other body.pdf
Hormones are distributed throughout the body in blood and other body.pdf
 
Explain the internet infrastructure stack. SolutionInternet inf.pdf
Explain the internet infrastructure stack. SolutionInternet inf.pdfExplain the internet infrastructure stack. SolutionInternet inf.pdf
Explain the internet infrastructure stack. SolutionInternet inf.pdf
 
Each hormone is known to have a specific target tissue. For each of t.pdf
Each hormone is known to have a specific target tissue. For each of t.pdfEach hormone is known to have a specific target tissue. For each of t.pdf
Each hormone is known to have a specific target tissue. For each of t.pdf
 
Describe the differences in the appearance of the sterile tube of Try.pdf
Describe the differences in the appearance of the sterile tube of Try.pdfDescribe the differences in the appearance of the sterile tube of Try.pdf
Describe the differences in the appearance of the sterile tube of Try.pdf
 
As we entered the 21st century, the Human Genome Project, a massive .pdf
As we entered the 21st century, the Human Genome Project, a massive .pdfAs we entered the 21st century, the Human Genome Project, a massive .pdf
As we entered the 21st century, the Human Genome Project, a massive .pdf
 
ActiveX is used by which of the following technologiesA. JavaB..pdf
ActiveX is used by which of the following technologiesA. JavaB..pdfActiveX is used by which of the following technologiesA. JavaB..pdf
ActiveX is used by which of the following technologiesA. JavaB..pdf
 
CBE 20. The following information is from financial statements (in mi.pdf
CBE 20. The following information is from financial statements (in mi.pdfCBE 20. The following information is from financial statements (in mi.pdf
CBE 20. The following information is from financial statements (in mi.pdf
 
Below is a simple Role Play Game (RPG) Simulator program.importjav.pdf
Below is a simple Role Play Game (RPG) Simulator program.importjav.pdfBelow is a simple Role Play Game (RPG) Simulator program.importjav.pdf
Below is a simple Role Play Game (RPG) Simulator program.importjav.pdf
 
A swim bladder allows a fish to Regulate its water content in sea wa.pdf
A swim bladder allows a fish to  Regulate its water content in sea wa.pdfA swim bladder allows a fish to  Regulate its water content in sea wa.pdf
A swim bladder allows a fish to Regulate its water content in sea wa.pdf
 

Recently uploaded

"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 

Recently uploaded (20)

"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 

Write a C++ program 1. Study the function process_text() in file.pdf

  • 1. Write a C++ program 1. Study the function process_text() in file "text_processing.cpp". What do the string member functions find(), substr(), c_str() do? //text_processing.cpp #include "util.h" #include "text_processing.h" #include using namespace std; int process_text( fstream &ifs, fstream &ofs, char target[] ) { string replace_str( "XXX" ); //hard-coded string for replacement int tlen = strlen( target ); //string length of target int max_len = 200; //maximum length of a line char s[max_len+1]; clear_screen(); //clear the screen while ( !ifs.eof() ) { int i2, i1 = 0, len=0; ifs.getline( s, max_len ); //get one line from file string str( s ); //construct a string object i2 = str.find ( target, i1 ); //find target len = i2 - i1; if ( i2 > -1 && len > 0 ){ //if target found print_text( str.substr( i1, i2 ).c_str() ); //print up to target ofs << str.substr( i1, i2 ); } while ( i2 > -1 ) { print_text_inverse ( target ); //highlight target ofs << replace_str; i1 = i2 + tlen; //new search position i2 = str.find ( target, i1 ); //find next target len = i2 - i1; if ( i2 > -1 && len > 0 ){ //found target print_text( str.substr( i1, len ).c_str() ); //print up to target
  • 2. ofs << str.substr( i1, len ); } } len = str.length() - i1; if ( len > 0 ) { //print the remainder print_text( str.substr( i1, len ).c_str() ); ofs << str.substr( i1, len ); } ofs << endl; getnstr( s, 1 ); //prompt for } //while ( !ifs.eof() ) restore_screen(); //restore the old screen return 1; } //text_processing.h #ifndef TEXT_PROCESSING_H #define TEXT_PROCESSING_H #include #include using namespace std; int process_text( fstream &ifs, fstream &ofs, char target[] ); #endif //util.h #ifndef UTIL_H #define UTIL_H #include #include #include #include #include using namespace std; void usage ( char program_name[] ); void clear_screen(); void print_text( const char *s ); void print_text_inverse( const char *s );
  • 3. void get_input_text( char *s, int max_len ); void restore_screen(); #endif //util.cpp #include "util.h" void usage ( char program_name[] ) { cout << "Usage: " << program_name << " infile outfile search_string" << endl; return; } /* The following are some curses functions. You can find the details by the command "man ncurses". But its use can be transparent to you. */ void clear_screen() { initscr(); scrollok ( stdscr, true ); //allow window to scroll } void print_text ( const char *s ) { printw("%s", s ); refresh(); } void print_text_inverse( const char *s ) { attron( A_REVERSE ); printw("%s", s ); attroff( A_REVERSE ); refresh(); } void get_input_text( char *s, int max_len ) { getnstr( s, max_len ); }
  • 4. void restore_screen() { endwin(); } //str_main.cpp #include "util.h" #include "text_processing.h" #include using namespace std; /* Note that grace_open() must be defined in same file as main(), otherwise the destructor of fstream will automatically close the opened file as it finds that its out of scope upon exiting the function. */ int grace_open( char *s, fstream &fs, char *mode ) { if ( mode == "in" ) fs.open ( s, ios::in ); else if ( mode == "out" ) fs.open ( s, ios::out ); if ( fs.fail() ) { cout << "error opening file " << s << endl; return -1; } else return 1; } //grace_open int main( int argc, char *argv[] ) { const int max_len = 200; char s[max_len+1]; char target[100]; if ( argc < 4 ) { usage( argv[0] ); return 1;
  • 5. } char *pin = argv[1]; //pointing to input filename char *pout = argv[2]; //pointing to output filename strcpy ( target, argv[3] ); //target for search fstream ifs, ofs; //input output filestream if ( grace_open ( pin, ifs, "in" ) < 0 ) return 1; //fail if ( grace_open ( pout, ofs, "out" ) < 0 ) return 1; //fail process_text( ifs, ofs, target ); return 0; } 2. Modify ( or write your own ) the program so that it does the following. 1. It displays a detailed help menu when one executes find_pat --help 2. It asks for an additional input argument, "replacing string" in addition to the three arguments described above. Namely, the four input arguments are: input filename, output filename, target string, replacing string. Instead of replacing the target strings by "XXX", replace them by the replacing string in the output file. For example find_pat text_processing.cpp out.txt in abc will replace all "in" by "abc" in "out.txt". 3. Highlight the "replacing string" on the screen instead of the "target string". ( Do not need to display the "target string" any more. ) Solution 1. int find(const string & s, int pos = 0) it searches the invoking string forsstarting at indexposand returns the index wheresis first located. substr() return a substring from the invoking string. c_str() it converts string to c styled string. it returns a const char* that points to a null-terminated c styled basic string. 2. #include #include #include #include
  • 6. #include #include #include #include #include using namespace std; void usage ( char program_name[] ) { cout << "Usage: " << program_name << " infile outfile search_string replaced_string" << endl; return; } void clear_screen() { initscr(); scrollok ( stdscr, true ); //allow window to scroll } void print_text ( const char *s ) { printw("%s", s ); refresh(); } void print_text_inverse( const char *s ) { attron( A_REVERSE ); printw("%s", s ); attroff( A_REVERSE ); refresh(); } void get_input_text( char *s, int max_len ) { getnstr( s, max_len ); } void restore_screen() { endwin();
  • 7. } int process_text( fstream &ifs, fstream &ofs, char target[], char rep_str[] ) { string replace_str( rep_str ); //hard-coded string for replacement int tlen = strlen( target ); //string length of target int max_len = 200; //maximum length of a line char s[max_len+1]; clear_screen(); //clear the screen while ( !ifs.eof() ) { int i2, i1 = 0, len=0; ifs.getline( s, max_len ); //get one line from file string str( s ); //construct a string object i2 = str.find ( target, i1 ); //find target len = i2 - i1; if ( i2 > -1 && len > 0 ){ //if target found print_text( str.substr( i1, i2 ).c_str() ); //print up to target ofs << str.substr( i1, i2 ); } while ( i2 > -1 ) { print_text_inverse ( rep_str ); //highlight target ofs << replace_str; i1 = i2 + tlen; //new search position i2 = str.find ( target, i1 ); //find next target len = i2 - i1; if ( i2 > -1 && len > 0 ){ //found target print_text( str.substr( i1, len ).c_str() ); //print up to target ofs << str.substr( i1, len ); } } len = str.length() - i1; if ( len > 0 ) { //print the remainder print_text( str.substr( i1, len ).c_str() ); ofs << str.substr( i1, len ); } ofs << endl; getnstr( s, 1 ); //prompt for
  • 8. } //while ( !ifs.eof() ) restore_screen(); //restore the old screen return 1; } int grace_open( char *s, fstream &fs, char *mode ) { if ( mode == "in" ) fs.open ( s, ios::in ); else if ( mode == "out" ) fs.open ( s, ios::out ); if ( fs.fail() ) { cout << "error opening file " << s << endl; return -1; } else return 1; } //grace_open int main( int argc, char *argv[] ) { const int max_len = 2000; char s[max_len+1]; char target[100]; char replace[100]; if ( argc < 5 ) { usage( argv[0] ); return 1; } char *pin = argv[1]; //pointing to input filename char *pout = argv[2]; //pointing to output filename strcpy ( target, argv[3] ); //target for search strcpy ( replace, argv[4] ); //target for search fstream ifs, ofs; //input output filestream if ( grace_open ( pin, ifs, "in" ) < 0 ) return 1; //fail if ( grace_open ( pout, ofs, "out" ) < 0 ) return 1; //fail
  • 9. process_text( ifs, ofs, target, replace ); return 0; }