Search code examples
c++stringfor-loopinsertiterator

core is being dumped


what is the problem in this code?

    string s; cin>>s;
    s[0]=s[0]-32;
    replace(s.begin(),s.end(),'s','$');
    replace(s.begin(),s.end(),'i','!');
    replace(s.begin(),s.end(),'o','(');
    for (auto i = s.begin(); i != s.end(); ++i)
    {
        if (*i == '(')
        {
            s.insert(i + 1, ')');
        }
    }
    s+=".";
    cout<<s<<endl;
cd "/home/parvez/Documents/cds/" && g++ Better_Passwords.cpp -o Better_Passwords && "/home/parvez/Do[parvez@HPLP cds]$ cd "/home/parvez/Documents/cds/" && g++ Better_Passwords.cpp -o Better_Passwords && "/home/parvez/Documents/cds/"Better_Passwords
unsophisticated
Segmentation fault (core dumped)

Solution

  • You may not change the string in the for loop such a way

    for (auto i = s.begin(); i != s.end(); ++i)
    {
        if (*i == '(')
        {
            s.insert(i + 1, ')');
        }
    }
    

    because after inserting a character the iterator i can be invalid. You need to write for example like

    for (auto i = s.begin(); i != s.end(); ++i)
    {
        if (*i == '(')
        {
            i = s.insert(i + 1, ')');
        }
    }