C++, string is seemingly truncating randomly

86 Views Asked by At

I'm trying to create a loop that'll remove multiple instances of a string of characters, in this case "123", and to replace them with the series of characters "168" for a class assignment. I have that part down, but for whatever reason, parts of the string are also seemingly truncating at random positions.

The code is as follows:

#include <iostream>
#include <string>
using namespace std;

int main() {
   string secretStr;
   int indx;
   
   cin >> secretStr;
   indx = 0;
// not part of the code, but I can only edit from here...
   
   while(secretStr.find("123") != string::npos){
    indx = secretStr.find("123");
    secretStr.replace(indx, indx+3, "168"); 
    indx = 0;
   }

//..to here
   cout << "Valid password: " << secretStr << endl;
   
   return 0;
}

I've tried messing around a bit with the while loop's condition, but haven't been able to find the right thing to check for. It's entirely possible I'm looking in the wrong spot too.

1

There are 1 best solutions below

0
Ietu On

So if we look at CPP string replace parameters, the second one should be len or the number of characters to be replaced by another string object. What you currently have is the indx+3 which now is the last position of the substring but you add + 3 to it so it gets a position 3 higher which is after the 123 and when you pass that to the replace it can cause truncation. What you need to do is just:

replace it with secretStr.replace(indx, 3, "168");

And just to test for example this would work in the behaviour you expect

#include <iostream>
#include <string>
using namespace std;

int main() {
   string secretStr;
   int indx;
   
   secretStr = "123pass123word123";
   indx = 0;
   
   while(secretStr.find("123") != string::npos){
    indx = secretStr.find("123");
    secretStr.replace(indx, 3, "168"); 
   }

   cout << "Valid password: " << secretStr << endl;
   
   return 0;
}

Let me know if you need any more help.