T
Tom
Please help I'm busy with my assigment and I'm stuck on the following:
I must enter a sentence and then replace words in the sentence, this
works fine but I must repeat it in a for loop. the first time the loop
starts it asks for the sentence and then the word it must look for and
then replace it with antoher. The problem is on the second time of the
loop it does not pause at the first question, it shows it but continue
to the last.
please see code below:
int n;
string Sentence, Sub1, Sub2;
int Position;
// We'll do this for 3 strings
for (n = 0; (n < 5); ++n)
{
// Input a sentence and two words
cout << "Enter a sentence: ";
cin >> Sentence;
cout << endl;
cout << "Enter a word to search for: ";
cin >> Sub1;
cout << "Enter a word to replace it with: ";
cin >> Sub2;
// Search for the Sub1 and replace all occurrences
// of it with the Sub2
Position = Sentence.find(Sub1);
while (Position != -1) {
Sentence.erase(Position, Sub1.size());
Sentence.insert(Position, Sub2);
Position = Sentence.find(Sub1);
}
I must enter a sentence and then replace words in the sentence, this
works fine but I must repeat it in a for loop. the first time the loop
starts it asks for the sentence and then the word it must look for and
then replace it with antoher. The problem is on the second time of the
loop it does not pause at the first question, it shows it but continue
to the last.
please see code below:
int n;
string Sentence, Sub1, Sub2;
int Position;
// We'll do this for 3 strings
for (n = 0; (n < 5); ++n)
{
// Input a sentence and two words
cout << "Enter a sentence: ";
cin >> Sentence;
cout << endl;
cout << "Enter a word to search for: ";
cin >> Sub1;
cout << "Enter a word to replace it with: ";
cin >> Sub2;
// Search for the Sub1 and replace all occurrences
// of it with the Sub2
Position = Sentence.find(Sub1);
while (Position != -1) {
Sentence.erase(Position, Sub1.size());
Sentence.insert(Position, Sub2);
Position = Sentence.find(Sub1);
}