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

1
  • You can create your own template <class T> std::string ToString(const T& x) { std::ostringstream ss; ss << x; return ss.str(); } Commented Oct 2, 2014 at 12:55

6 Answers 6

1

Use :

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

Specifies stream open mode as ate

See here

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

1 Comment

What is the reason for ate?
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).

Comments

1
ostringstream ss;
ss << "dice_" << n << ".dat";
myfile.open(ss.str().c_str());

1 Comment

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.)
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";

1 Comment

Thanks for your response, I can't use 'to_string' as this is only supported in c++ 11 not 98.
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";
//...

Comments

0

Convert your int with boost:

boost::lexical_cast<std::string>(yourint) from boost/lexical_cast.hpp

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.