I got a error like to_string was not declared in scope
Set your compiler to use (at least) c++11.
(In their current positions, and relying on counter always being less than or equal to 9) you could replace both occurrences of to_string() with (char)( '0' + counter )
or you could write your own version of to_string() using, e.g., stringstream. However, both these approaches are suboptimal. You would be much better in the long run either upgrading your compiler or setting one of its options so that you can write (at least) c++11 code.
In the meantime you can try the code in cpp.sh using the little gear-wheel icon to top-right of the code sample.