Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ newbie: my loop should CHANGE a string, then print the string to a file. But it is ADDING to the string

I have written C++ code for performing calculations. There is a loop in the code. At the end of each loop, I want to:

1) Get the time, a calculation result.

2) Make a name for a file. The name should contain the time.

3) Print the file name into an external file. Each new loop should overwrite the file name from the previous loop.

The first problem I had was that I could not delete the OLD file name. So when my calculation was finished, the name was (for example): calculationForRestartFile_0.0005476490.004925880.01763170.04375820

instead of: calculationForRestartFile_04375820

I have updated this question to incorporate Mat's advice. Thanks Mat. But now I'm not getting anything in the external file. Can anyone see where I'm going wrong? I would be very grateful for 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
like image 376
Ant Avatar asked Dec 10 '25 20:12

Ant


1 Answers

The issue is that this line is adding to your stringstream inside the loop. You are never resetting its contents.

storeNumberForConversion << global_time << flush;

The simplest thing to do is to move the declaration of storeNumberForConversion inside your loop so it is created empty just before you use it.

Alternatively you could reset it after your formatting operation.

storeNumberForConversion.str( std::string() );
like image 184
CB Bailey Avatar answered Dec 12 '25 09:12

CB Bailey