I am attempting to write a program which will:
- Open 1.txt (which contains the strings we need to find)
- Read them into a new string array, seperate elements
- open 2.txt (which contains the document we want to find strings in to replace)
- Read line -> compare the input string line literal with all the elements we found in 1.txt
- If match, replace the offending string, add the line to a char array - HOWEVER, if it matches, there may also be another offending string on the same line, how can I compensate?
- else, add the line to char array ()
- Write the char array to a new output file (which will contain the original text + replaced strings)
Essentially, like pressing CRTL + H on a text document, replacing the strings, except multiple times! (around 70 strings to replace)
First of all, is this even possible? If so, what would be the best way you can recommend in doing this.
By the way, I generate random strings as replacement, don't worry about that.
Here is what I have so far:
.... CODE above here
ifstream instubFile;
ofstream outstubFile;
outstubFile.open("Temp.txt",ios::out);
instubFile.open("stub.txt",ios::in | ios::out);
instubFile.seekg(0, instubFile.end);
unsigned int m_uNumChars = instubFile.tellg();
instubFile.seekg(0,instubFile.beg);
string inBuf;
if (instubFile) // if it opened the file
{
// read each line, check for any string matches
// if string match, replace it, add line to output string
// else, add the line to output string
while(getline(instubFile,inBuf)) // read the line
{
cout << numberoflines << endl;
for (int i = 0; i < numberoflines ; i++) // compare chars in buffer with toreplace string
{
int m_iSize = inBuf.find(m_szToReplace[i]);
cout << m_iSize << endl;
if (m_iSize > 0)
{// found
inBuf.replace(m_iSize,m_szReplacement[i].length(),m_szReplacement[i]);
outstubFile << m_szReplacement[i] << endl;
}
}
}
}
else
{
cout << "Could not open stub.txt" << endl;
}
cout << inBuf << endl;
cin.get();
delete[] m_szReplacement;
delete[] m_szToReplace;
return 0;
}
/*
int spot = inBuf.find(m_szToReplace[i]);
if(spot >= 0)
{
string tmpstring = inBuf.substr(0,spot);
tmpstring += m_szReplacement[i];
tmpstring += inBuf.substr(spot+m_szToReplace[i].length(), inBuf.length());
inBuf = tmpstring;
}
*/
It works fine up until retrieving the line, in which I am not sure of how to go out doing (comparing strings)?