0

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

3
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by jonsca
0

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.

0

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.

1

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

Edited by dkalita: n/a

0

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

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

Edited by jonsca: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.