Why does the string become a loop?

I am trying to make it so it replaces every r in a word with 3 r's. Ex: there
}
Last edited on
It is simpler to create a new string with the replacements;
and if the original string needs to be modified, at the end: original_string = modified_string ;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

int main()
{
    std::cout << "enter a string: " ;
    std::string original_string ;
    std::getline( std::cin, original_string ) ;

    // replace every single 'r' with "rrr" to form the modified string
    std::string modified_string ;
    for( char c : original_string ) // for each character c in the original string
    {
        if( c == 'r' ) modified_string += "rrr" ;
        else modified_string += c ; // not 'r', append it unchanged
    }

    std::cout << original_string << '\n' << modified_string << '\n' ;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

int main()
{
   string text;
   cout << "Enter a string: ";   getline( cin, text );
   int pos = 0;
   while( ( pos = text.find( "r", pos ) ) != string::npos )
   {
      text.insert( pos, "rr" );
      pos += 3;
   }
   cout << "Modified string is " << text;
}

Enter a string: Hurry, hurry!
Modified string is Hurrrrrry, hurrrrrry!
Last edited on
Your problem:

You find an 'r', insert three 'r'. Now you have four 'r'.
When you do this loc = intext.find('r', loc + 2); you will find the 'r' recently inserted. Thus you will infinitely insert 'r'.
@restinpasta,

Please don't delete your post: people took trouble to answer it carefully with alternative code and an explanation of your original error.

This forum is a good educative resource (I learnt my C++ from reading it and I'm still learning from it). Here, for reference, is your original post in full

 I am trying to make it so it replaces every r in a word with 3 r's. Ex: there would become therrre.
But right now when I run it it just is an infinite loop, how would I fix this? Thanks!
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(void){
string intext;
int loc;
cout << "Input a string\n";
getline(cin, intext);
cout << "Before changes, the string is:\n";
cout << intext << endl;
loc = intext.find('r');
while (loc != -1){
intext.insert(loc, "rrr");
cout << intext << endl;
loc = intext.find('r', loc + 2);
}
cout << "final result is:\n";
cout << intext << endl;
return 0;

}
Topic archived. No new replies allowed.