Here is a C++ snippet which inserts a dot .
before every character in the string.
Here's my code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin >> s;
for (auto it = s.begin(); it != s.end(); it++)
{
s.insert(it, '.');
it++;
}
cout << s;
}
Here I am using iterators and after inserting .
before a character. I am incrementing iterator because the insert method sets the iterator to the position where the new character is inserted.
But something weird is happening, I am getting runtime error for some inputs:
For example:
Input: abcde
Output: .a.b.c.d.e
Input: abcdef
Output: .a.b.c.d.e.f
Input: abcdefg
Output: .a.b.c.d.e.f.g
Input: abcdefgh
Output: Getting runtime error
~~Dr.M~~ Error #1: UNADDRESSABLE ACCESS beyond heap bounds: reading 0x10fb4fa7-0x10fb4fa8 1 byte(s)
~~Dr.M~~ # 0 replace_memmove [d:\drmemory_package\drmemory\replace.c:802]
~~Dr.M~~ # 1 std::char_traits<>::move [C:/Programs/mingw-w64-7/lib/gcc/i686-w64-mingw32/7.3.0/include/c++/bits/char_traits.h:342]
~~Dr.M~~ # 2 std::__cxx11::basic_string<>::_S_move [C:/Programs/mingw-w64-7/lib/gcc/i686-w64-mingw32/7.3.0/include/c++/bits/basic_string.h:349]
~~Dr.M~~ # 3 std::__cxx11::basic_string<>::_M_replace_aux [C:/Programs/mingw-w64-7/lib/gcc/i686-w64-mingw32/7.3.0/include/c++/bits/basic_string.tcc:407]
~~Dr.M~~ # 4 std::__cxx11::basic_string<>::insert
I am not able to understand why this is happening, please help me in this.
Note: I know there are other ways of solving this problem but I am curious to know what is happening here.