I'm in charge of helping first year students with this program where we need to find a word in a string, a change it by another given word. i wrote it as such
#include <iostream>
#include <string>
using namespace std;
void changeWord(string &texto, string wordB, int pos, int sizeA)
{
int auxi;
string antes, depois;
for(auxi = 0; auxi < pos; auxi++)
{
antes[auxi] = texto[auxi];
cout<< "Antes["<< auxi<< "]: "<< antes[auxi]<< endl;
}
for(auxi = 0; auxi+pos+sizeA < texto.length(); auxi++)
{
depois[auxi] = texto[auxi+pos+sizeA];
cout<< "Depois["<< auxi<< "]: "<< depois[auxi]<< endl;
}
cout<< "Antes: "<< antes<< " Depois: "<< depois<< endl;
texto = antes + wordB + depois;
cout<< "Texto:"<< texto<< endl;
}
void findWord(string texto, string wordA, string wordB)
{
int auxi;
for(auxi = 0; auxi < texto.length(); auxi++)
{
cout<< "texto["<< auxi<< "]: "<< texto[auxi]<<" wordA[0]: "<< wordA[0]<< endl;
if(texto[auxi] == wordA[0])
{
int auxj;
for(auxj = 1; auxj < wordA.length() && texto[auxi+auxj] == wordA[auxj]; auxj++)
{
cout<< "texto["<< auxi+auxj<< "]: "<< texto[auxi+auxj]<< " wordA["<< auxj<< "]: "<< wordA[auxj]<< endl;
}
if(auxj == wordA.length())
{
changeWord(texto, wordB, auxi, wordA.length());
}
}
}
}
int main()
{
string texto = "Isto_e_um_texto_qualquer";
string wordA, wordB;
cin >>wordA;
cin >>wordB;
findWord(texto, wordA, wordB);
return 0;
}
I would expect this to work, and to some degree it does what i wanted up until in function call to 'changeWord()' when i try to output both 'antes' and 'depois' strings.
These work inside their respective loops, printing to screen the expected char:
cout<< "Antes["<< auxi<< "]: "<< antes[auxi]<< endl;
cout<< "Depois["<< auxi<< "]: "<< depois[auxi]<< endl;
This does not:
cout<< "Antes: "<< antes<< " Depois: "<< depois<< endl;
both 'antes' and 'depois' are printed as blank. In addition the program crashes when it gets to this line:
texto = antes + wordB + depois;
I assume it is for the same reason it cant print them in the previous line. What am I doing wrong?