C ++ newbie: my loop should CHANGE the line and then print the line in the file. But this is ADD to the line

I wrote C ++ code to do the calculations. There is a loop in the code. At the end of each cycle, I want:

1) Get the time, the result of the calculation.

2) Create a name for the file. The name must contain the time.

3) Print the file name to an external file. Each new cycle should overwrite the file name from the previous cycle.

The first problem I ran into was that I could not delete the name of the OLD file. So when my calculations were finished, the name was (for example): calculationForRestartFile_0.0005476490.004925880.01763170.04375820

instead: calculationForRestartFile_04375820

I updated this question to include Mat advice. Thanks Mat. But now in the external file I get nothing. Can anyone see where I'm wrong? I would really appreciate any advice.

// Above loop:
  std::string  filename = "calculationForRestartFile_";  // Part of the file name that ALL files should have
  ofstream fileNameAtHighestTimeStream;    

  std::string       convertedToString;                  // This and the line below:
  std::stringstream storeNumberForConversion;           // For storing a loop number/time as a string

// Inside loop:
    storeNumberForConversion << global_time << flush;       // Turn the time/loop number into a string that can be added to the file name for a particular loop
    convertedToString = storeNumberForConversion.str();

    fileNameAtHighestTimeStream.open ("externalFile", ios::out | ios::app ); 
    fileNameAtHighestTimeStream << filename << convertedToString << endl;    // Append the time/loop name to the file name and write to the external file
    fileNameAtHighestTimeStream.close();

// End loop
+3
source share
2 answers

The problem is what this line adds to your stringstreaminside loop. You never reload its contents.

storeNumberForConversion << global_time << flush;

The simplest thing is to move the ad storeNumberForConversioninside your loop so that it is empty shortly before it is used.

Alternatively, you could reset after the format operation.

storeNumberForConversion.str( std::string() );
+5
source

Why not just write the time directly to the file?

+1
source

All Articles