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.
So if we look at CPP string replace parameters, the second one should be
lenor the number of characters to be replaced by another string object. What you currently have is theindx+3which now is the last position of the substring but you add + 3 to it so it gets a position 3 higher which is after the123and when you pass that to thereplaceit 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
Let me know if you need any more help.