Unusual Error Message

Hey all!

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() {
using namespace 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.

All help will be greatly appreciated!
Look at your loop condition:

for (i=0; i=str.length(); i++) {


This is basically causing the loop to loop infinitely.

why this would cause the program to stop, I'm not sure, but fix that and I'm sure you will fix the problem

(it probably was supposed to be '<', not '=' -- although I don't see the significance of 'i' here, so maybe this should be a while loop instead?)
Thanks for the reply. I changed it to
 
for (i=0; i<str.length(); i++) {

and yet I still get the same error.

Any more ideas?
Last edited on
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() {
using namespace 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 :)
Topic archived. No new replies allowed.