-1

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)
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Parvez Ali
  • 13
  • 2
  • Questions seeking debugging help should generally provide a [mre] of the problem, which includes a function `main` and all `#include` directives. This allows other people to easily test your program, by simply using copy&paste. – Andreas Wenzel Jan 28 '23 at 20:55
  • `s.insert(i + 1, ')')` invalidates iterators into `s`, including `i`. The subsequent `++i` then exhibits undefined behavior. – Igor Tandetnik Jan 28 '23 at 20:56

1 Answers1

1

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, ')');
    }
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335