string, insert function

I want to insert '.' before 'A' or 'a', so what's wrong with this code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include<iostream>
#include<string>

using namespace std;

int main()
{
    string str = "Car is black.";

    for(int i=0; i<str.length();i++)
    {
        if(str[i]=='A' || str[i]=='a')
        {
            str.insert(i-1,1,'.');
        }
    }
    cout<<str<<endl;
    return 0;
}
Last edited on
Well, it finds an 'a', inserts dot before it (therefore current character is now dot and next is 'a'), moves to the next characer, notices that it is 'a' again, inserts dot... INFINITE LOOP!
Last edited on
So how can I insert the dot before 'a'?!
And thanks for reply :))
1) you can save result in another variable (not modifying current one)
2) You can just increment i after inserting.
ok , Thank you for this helpful information :)
Topic archived. No new replies allowed.