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!

1
  • 1
    Print ss.str() each time. Commented Dec 22, 2013 at 15:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.