Dear friends:
I wrote the following c++ codes to create a series of filenames as
"iteration number.dat".

#include <iostream>

#include<string>
#include<sstream>
using namespace std;


int main()
{

string outbuffer;
ostringstream outs(outbuffer);

for (int i=0;i<5;i++)
{
    outs<<i<<".dat";
    cout<<outs.str()<<endl;
}

    cout<<outbuffer;


    return 0;
}

I tried to use the ostringstream to transform the iterger itreation number "i" to char. when i output the resutls , it give me the following.

0.dat
0.dat1.dat
0.dat1.dat2.dat
0.dat1.dat2.dat3.dat
0.dat1.dat2.dat3.dat4.dat

Process returned 0 (0x0)   execution time : 0.042 s
Press any key to continue.

It is evident that outs.str() can give accurate results , but the variable "outbuffer" is empty.
Could you please tell me what is the reason?
and how to prevent the outstream to append to the former one. it should give me the filenames as:
0.dat
1.dat
2.dat
3.dat
4.dat
Any feedback is wellcome!
Regards

you are not resetting the stringbuffer to ""(empty string) after every iterations which is the reason why it is keeping the previous values.

Reset the stringbuf at the end of every iterations then only you will get the expected outputs.

you are not resetting the stringbuffer to ""(empty string) after every iterations which is the reason why it is keeping the previous values.

Reset the stringbuf at the end of every iterations then only you will get the expected outputs.

Thank you very much! it doesnot work. the outbuffer is empty. When i use
cout<<outbuffer;
it only gives me nothing.

there is nothing in the outbuffer variable.
You are modifying the variable "outs" everytime. So reset it after every itereations to "".

When you wrote

ostringstream outs(outbuffer);

the outs variable is initialised with the string in the variable "outbuffer", it does not correlate to that variable.
So reset "outs". And at the end print outs.str() instead of "outbuffer".

Please show the code where you are resetting it to "".

Edit: Try his ^^^^^^ suggestion first.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.