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' ;
}
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'.
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;
}