Inside your loop you are not resetting the stringstream
object
ss <<"PMap" << j <<".txt" << endl;
thus you keep appending stuff to the stringstream without removing the previous stuff added. Replace the above line in your loop with the following 2 lines to correctly clear the stringstream
at each iteration.
ss.str("");
ss <<"PMap" << j <<".txt" << endl;
This is why the code only works once - the first time the stream is cleared, but subsequent iterations it contains all the characters you have added at previous iterations.