my teacher ask me to create this program but I only know how to do B task . He gave me a sample text and tell me to input it then do some actions (below). I looked up for task A but he said that we need to do the code like this. I spent days for the book "C++ from controls Structures through Objects" which he required for the course but I cannot find the chapter that relates to "FIND STRING".
string text = "The aa Art of Computer Programming";
int pos = 0;
string target = "aa";
pos = text.find(target, 0);
}
But the problem is that I don't know how to change pos = text.find(target, 0);
=> pos = "input file ?".find(target,0)
.
a. Search a text. The program receives the search-word from a user, searches the content of the file and returns whether matching words are found or not and how many.
b. Search and replace a text. The program reads the search-word and the replacement-word from a user and it replaces the matching words in the content of the file with replacement-word.
c. Determines the number of words.
d. Determine the number of characters—including white-space
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string strTarget = " "; //String to search
string strNew = " "; //String To re
ifstream filein("test.txt"); //File to read from
ofstream fileout("replaced.txt"); //Temporary file
int pos = 0;
int menuItem = 0;
cout << "What do you want to do today ?" << endl;
cout << "1. Search a text " << endl;
cout << "2. Search and replace the text " << endl;
cout << "3. Determine number of word" << endl;
cout << "4. Determine number of character " << endl;
cin >> menuItem;
switch (menuItem)
{
case 1:// search
system("cls");
cout << "Please enter the text you want to search" << endl;
cin >> strTarget;
break;
case 2: // search and replace
cout << " Tell me the text you want to replace " << endl;
cin >> strTarget;
cout << " So what It's suppose to be ? " << endl;
cin >> strNew;
if (!filein || !fileout) //if both files are not available
{
cout << "Error opening files!" << endl;
return 1;
}
string strTemp;
//bool found = false;
while (filein >> strTemp)//it will check line from test to strTemp string
{
if (strTemp == strTarget)//if your word found then replace
{
strTemp = strNew;
//found = true;
}
strTemp += " ";
fileout << strTemp;//output everything to fileout(temp.txt)
//if(found) break;
}
return 0;
}
}
- the notes of the code is not really correct cause I change the name a little bit.. i know this kinda ridiculous to most programmers but I'm new to CS and surething I have trouble with any code out of the book. please help me instead of being rude. Big thanks! i wish my college had tutor of CS but somehow they cannot afford a cs tutor. That's why i need help from you guys .