0

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!

KuroNeko
  • 319
  • 2
  • 8
  • 17

2 Answers2

4

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.

mathematician1975
  • 21,161
  • 6
  • 59
  • 101
  • do not know yet..there seems to be another problem somewhere else so I can not run the prog yet..Will post as soon as I can run it.Thanks. – KuroNeko Jan 09 '14 at 05:41
  • @mathematician1975..Thanks,that did work..The problem was also that the ifstream was not being reset every time.So I put that declaration and stringstream declaration inside the loop and it worked! – KuroNeko Jan 15 '14 at 18:49
1

Your loop is too small - change it to for (j = 1; j <= 7; j++).

enedil
  • 1,605
  • 4
  • 18
  • 34