-4

Foreword: Hello. I've read several questions/answers and spent an hour trying to debug my code but to no avail, so here goes.

Topic: I'd like to write a C++ code that creates several files. These files have names made of letters and integers.

State of affairs: I've managed to find how to make the filenames, but I still have a problem to reset something (I don't know what), because at present the names keep adding up, i.e. the first file is File_1_1.dat but the second becomes File_1_1.datFile_1_2.dat instead of File_1_2.dat

Things I've tried: memset, scope, fill. But nothing seems to be working. Below is my code. I believe it is a bad mix of C++ and C but I couldn't understand how to make that only C++.

Thank you for your help!

#include <iostream> 
#include <fstream>
#include <iomanip> 
#include <stdlib.h>
#include <string>
#include <cstring>
#include <sstream>
#include <assert>

using namespace std;

// ... and in the function in question ...

ofstream myfileOUT;

stringstream sstrm;
string s_filenameOUT, pt1="File_", pt2="_", pt3=".dat";
char filenameOUT[1000];

for(i=1;i<10;i++){
  for(j=1;j<6;j++){

   //first we construct a string that 
   //is a concatenation of sentence and numbers
   sstrm << pt1 << i << pt2 << j << pt3;
   s_filenameOUT=sstrm.str();

   //then we convert it to char
   strncpy(filenameOUT, s_filenameOUT.c_str(), sizeof(filenameOUT));
   filenameOUT[sizeof(filenameOUT) - 1] = 0;

   //and finally we can create the file with the char
   myfileOUT.open(filenameOUT,ios::out);
   myfileOUT.close();

   /* rest of code here that writes in the file */

  }
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Butini
  • 101
  • 3

2 Answers2

4

You do not reset a stringstream, so it adds up. You can clear it like this:

sstrm.str("");

or better just make sstrm local inside a loop:

for... {
    for... {
        stringstream sstrm;

Even better use ostringstream as you do not need to read from sstrm.

Also, why do you use sstrm value in such a non-trivial way? Why not simply

myFileOut.open(sstrm.str().c_str(),ios:out);

?

Petr
  • 9,812
  • 1
  • 28
  • 52
0

You have to clear/reset the stringstream sstrm in each iteration of your loop.

adjan
  • 13,371
  • 2
  • 31
  • 48