do-while loop with string not working?

I have the following code. As noted, the top part(before the loop) works perfectly (yay!), but once I enter the loop, it does not work. I am trying to replace "his" with "his or her" in this sentence: "It is his money, his time, and his life!"

The first part of the code gives me this:
"It is his or her money, his time, and his life!"

The loop gives me:
"It is hhis or heror her money, his time, and his life!"

How can I fix this?
Thanks in advance!
Also, I have to use find and replace - no substitutes are allowed.





// assignment7E.cpp


#include <iostream>
#include <cmath>
#include <string>

using namespace std;




int main()
{

char message[100];
cout<<"Enter the message to be changed: "<<endl;
cin.getline(message,100);
cout<<"Original message is as follows: "<<message<<endl;
cout<<" "<<endl;

string changed=message;


int start2=changed.find(" his",0);

string secret;
secret=changed.replace(start2+1,3,"his or her");
cout<<secret<<endl;
cout<<" "<<endl;

//above code works fine
//Loop has problems :(

string final;
start2=0;

do
{

start2=changed.find("his",0);

string final;
final=changed.replace(start2+1,3,"his or her");

cout<<"The new message is as follows: "<<final<<endl;

}while(start2==string::npos);

return 0;
}


Last edited on
I was able to get rid of the top part, and just use the loop, but now it only goes through the loop once.



#include <iostream>
#include <cmath>
#include <string>

using namespace std;


int main()
{

char message[100];
cout<<"Enter the message to be changed: "<<endl;
cin.getline(message,100);
cout<<"Original message is as follows: "<<message<<endl;
cout<<" "<<endl;

string changed=message;

int start2;

do
{

int start2=changed.find("his",0);

string final;
final=changed.replace(start2,3,"his or her");

cout<<"The new message is as follows: "<<final<<endl;

}while(start2==string::npos);

return 0;
}







Is your problem solved, if so use the solved button.
Otherwise, what is your question/

Please use code tags (the <> button) when pasting code.
No, it is not solved.
My problem is that it is only entering the code once. I forced it to loop a few times, and it gave me this:
"his or her car, his life, his money" (Different words, but same idea)
"his or her or her car, his life, his money"
"his or her or her or her car, his life, his money"

It SHOULD be:
"his or her car, his or her life, his or her money"

QUESTION: How do I make it look how it should?

And sorry about the code tags - this is only my second time posting in here, and I didn't know how to do that. sorry!
Topic archived. No new replies allowed.