I am trying a short code that uses an array, I basically want to replace the word hate for love when I call my function WordReplace but I keep printing the same thing:
I don't love c++ I don't love c++
I have tried different things but I am not sure what is wrong
#include <iostream>
#include <string>
using namespace std;
void WordReplace(string*x, int start, int end, string g, string w)
{
for (int z = start; z <= end; z++)
{
if (x[z] == g)
x[z] == w;
cout << x[z]<<" ";
}
}
int main()
{
string x[4] = {"I", "don't", "hate", "c++"};
for (int i = 0; i < 4; i++)
{
cout << x[i] << " ";
}
cout << endl;
WordReplace(x, 0, 3, "hate", "love");
cout << endl;
return 0;
}
x[z] == wshould bex[z] = w. Read about the difference between=and==in your favorite C++ textbook.gandwdon't do it for me. But @IgorTandetnik has your answer.std::replacealgorithm function, which does the job in one line of code. The point is that if you're writing code that has the feeling that it has to have been done millions of times before (like replacing x with y), then there is more than likely an STL algorithm function that does the job (if not a set of functions).std::stringreplaced withintwarning "statement has no effect" is produced as expected.std::vector<std::string>instead of an array. A lot easier to pass to functions.