4

I am using c++ 98 (as that is what is installed on the university server). I am trying to save an output to a file. The filename has to be dice_N.dat where N is the number of rolls of the dice, which I have called n_trials. I have tried following the suggestions on inserting int variable in file name. When using the second suggestion I get the output N.dat. Here the snippet of my code which tries to do this:

    ostringstream fileNameStream("dice_");
    fileNameStream << n_trials << ".dat";
    string fileName = fileNameStream.str();  
    ofstream myfile;
    myfile.open(fileName.c_str());

I can't use to_string as this is not supported in c++ 98

Community
  • 1
  • 1
thewire247
  • 795
  • 1
  • 9
  • 24
  • You can create your own `template std::string ToString(const T& x) { std::ostringstream ss; ss << x; return ss.str(); }` – Neil Kirk Oct 02 '14 at 12:55

6 Answers6

1

Use :

ostringstream fileNameStream("dice_", std::ios_base::ate);

Specifies stream open mode as ate

See here

P0W
  • 46,614
  • 9
  • 72
  • 119
1

The problem appears because the std::stringstream overwrites the initial buffer.

Try this instead:

ostringstream fileNameStream;                    // let this be empty
fileNameStream << "dice_" << n_trials << ".dat"; // and pass "dice_" here
string fileName = fileNameStream.str();  
ofstream myfile;
myfile.open(fileName.c_str());

Alternately, you can create the ostringstream with std::ios::ate as a flag (ate tells the stream it should append at the end of the input (and then, you can still pass the "dice_" part in the constructor and it will not be overwritten).

utnapistim
  • 26,809
  • 3
  • 46
  • 82
1
ostringstream ss;
ss << "dice_" << n << ".dat";
myfile.open(ss.str().c_str());
Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
  • 1
    That should be `std::ostringstream`, but otherwise, this is the route I would have taken. (I always construct `std::ostringstream` empty. Somehow, it seems more logical; an output stream doesn't have any content until you inject it.) – James Kanze Oct 02 '14 at 13:10
0

You can use std::to_string to create a std::string from the int, then concatenate.
In fact, I would just make the whole filename this way

std::string fileName = "dice_" + std::to_string(n_trials) + ".dat";
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

Simply provide all three parts with the << operator, it is also more readable since you don't mix different syntaxes:

ostringstream fileNameStream;
fileNameStream << "dice_" << n_trials << ".dat";
//...
leemes
  • 44,967
  • 21
  • 135
  • 183
0

Convert your int with boost:

boost::lexical_cast<std::string>(yourint) from boost/lexical_cast.hpp
Nejc Galof
  • 2,538
  • 3
  • 31
  • 70