I am editing an existing C++ code such that it opens multiple files using stringsteam. I have a loop with an integer going from 1 to 7, and there are 7 files that I need to open. The files are named PMAP1.txt ... PMAP7.txt. I am trying to open it this way:
ifstream precipfile;
int j = 0;
stringstream ss;
string FileName;
for(j=1;j<6;j++){
ss <<"PMap" << j <<".txt" << endl;
FileName = ss.str();
precipfile.open(FileName.c_str(),ios::in);
if( !precipfile.good() )
ReportFatalError( "Unable to find or open precipfile" );
}
This does not work for some reason.It returns "Unable to find or open precipfile". But if I open one file just by using one filename directly it works.Like:
string FileName = ( "PMap.txt" );
precipfile.open(FileName.c_str());
This works.Please help!
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.