Write a short program thats reads a file called text.txt that replaces all words that begins with the letter f and is replaced with the word frog. Now i have a jeist of how to replace words with another word however i am unsure how to find words only starting with f and replacing the string.
This is what ive gotten so far which isnt correct:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
void get_input_from_user(string tag,string &input);
void replace_string(string in_text, string find_word, string replace_word,string &out_text);
int main()
{
ifstream inFile;
string infilename = “source.txt”;
string line = “”;
string input = “”;
string in_text = “”;
string find_word =“”;
string replace_word = “”;
string out_text = “”;
inFile.open(infilename.c_str());
if (inFile.fail())
{
cout << “The file “ << infilename;
cout << ” cannot be opened for reading.”<<endl;
cout << “Exiting.”<<endl;
exit(1);
}
while(getline(inFile,line))
in_text = in_text + line;
inFile.close();
cout << “Give me a string to find: “;
getline(cin,find_word);
cout << “Give me a replacement string: “;
getline(cin,replace_word);
replace_string(in_text, find_word,replace_word,out_text);
cout << out_text;
}
void replace_string(string in_text, string find_word, string replace_word,string &out_text)
{
int start_loc = 0;
int char_num = 0;
ostringstream outString;
while(char_num < in_text.length())
{
start_loc = in_text.find(find_word,char_num);
if (start_loc != string::npos )
{
outString << in_text.substr(char_num,start_loc);
outString << replace_word;
char_num = start_loc+find_word.length();
}
else
{
outString << in_text.substr(char_num,in_text.length()-char_num);
char_num = in_text.length();
}
}
out_text = outString.str();
return;
}