Im in c and im trying to work a homework problem but the out
Im in c++ and im trying to work a homework problem but the output is not the right answer and I dont know what Im doing wrong in my code. Bellow is my code name int replace(char * str, char ch1, char ch2). However the int main(){} was provided by the professor. Our homework is based on pointers and strings. This is the question:
Write the function replace(). The function has three parameters: a char * s, a char c1 and a char c2. Replace all instances of c1 with c2. Return a pointer to the first character in s.
#include <string>
#include <iostream>
#include <cassert>
using namespace std;
int replace(char * str, char ch1, char ch2)
{
int changes=0;
while(*str!=\'\\0\')
{
if(*str==ch1)
{
*str=ch2;
changes++;
}
str++;
}
return changes;
}
int main()
{
cout << \"\ replace(dog, \'o\', \'i\') expects \\\"Labradiidle\\\"\" << endl;
cout << \" -- \\\"\" << replace(dog, \'o\', \'i\') << \"\\\"\" << endl;
}
Solution
char& replace(char * str, char ch1, char ch2)
{
char *ref;
ref=str;//assign ref the pointer to first character
while(*str!=\'\\0\')
{
if(*str==ch1)
{
*str=ch2
}
str++;
}
return ref;
}
//dont count no of changes instead assign address of //first character to another char pointer

