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;
}
Ad

More Related Content

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

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
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
Daniel Nyagechi
 
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 c
gkgaur1987
 
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
String Manipulation Function and Header File Functions
Bosco Technical Training Society, Don Bosco Technical School (Aff. GGSIP University, New Delhi)
 
C q 3
C q 3C q 3
C q 3
Rahul Vishwakarma
 
array, function, pointer, pattern matching
array, function, pointer, pattern matchingarray, function, pointer, pattern matching
array, function, pointer, pattern matching
Shakila Mahjabin
 
Sbaw091006
Sbaw091006Sbaw091006
Sbaw091006
Atsushi Tadokoro
 
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
 
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 c
gkgaur1987
 
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
 
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 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
 

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

Recently uploaded (20)

Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Ad

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; }
  翻译: