I keep getting an usual error message whenever trying to run this piece of code. It appears whenever I run it (not a compiling error).
The error is: This application has requested the runtime to terminate it in an usual way. Please contact the application's support team for more information.
The code is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
int main() {
usingnamespace std;
string str = "abed bed ad bed bad ade";
int i;
for (i=0; i=str.length(); i++) {
int position1 = str.find("a");
str.insert(position1,"10,6,3");
int position2 = str.find("a");
str.erase(position2,1);
}
cout <<str <<endl;
system("pause");
return 0;
}
This interesting thing is, it works perfectly fine if I remove the "for" loop, except that it only replaces and removes one instance of "a" and not all of them.
I solved the problem!
Basically I hadn't handled the fact that str.find("a) might will become false (-1) after four loops but my code would still try to replace a non-exsistent "a" in the string. Changed the code to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <string>
int main() {
usingnamespace std;
string str = "abed bed ad bed bad ade";
int i;
for (i=0; i<str.length(); i++) { //I also had to change this from "=" to "<"
int positionA1 = str.find("a");
if (positionA1!=-1) {
str.insert(positionA1,"10,6,3,");
int positionA2 = str.find("a");
str.erase(positionA2,1);
}
}
cout <<str <<endl;
system("pause");
return 0;
}
As I commented, I also had to change the for condition, so thanks for that :)