string, insert function

May 16, 2014 at 7:59pm
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 May 16, 2014 at 8:00pm
May 16, 2014 at 8:03pm
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 May 16, 2014 at 8:04pm
May 16, 2014 at 8:08pm
So how can I insert the dot before 'a'?!
And thanks for reply :))
May 16, 2014 at 8:11pm
1) you can save result in another variable (not modifying current one)
2) You can just increment i after inserting.
May 16, 2014 at 8:18pm
ok , Thank you for this helpful information :)
Topic archived. No new replies allowed.