Question

I've got a deque in c++ and I want to push back to it numbers from 1 to 17. I wrote the following code: string Result;

string Result;          

ostringstream convert;   

for(int i=1; i< 18; i++){

    convert >> i;      
    Result = convert.str(); 
    temp.push_back(Result);   
}

cout <<"temp at_"<< temp.at(16) << endl;

The problem is that temp.at(16) prints with cout: 1234567891011121314151617 and not 17, how is it possible to add every time just the current i?

Edit: the above code works:

string Result;          
ostringstream convert;   
for(int i=1; i< 18; i++){

            convert.str(std::string());
    convert << i;      
        Result = convert.str(); 
    temp.push_back(Result);   
}

cout <<"temp at_"<< temp.at(16) << endl;
Was it helpful?

Solution

It looks like you are not clearing your converter,

 1234567891011121314151617 

are all your integers you iterated

Assuming, convert is:

std::stringstream convert;

you can clear it before each use using:

convert.str(std::string());
convert << i;

OTHER TIPS

I would suspect the problem lies in convert << i. If it works how I think it does, you're appending numbers in a string-like fashion onto that variable, and it just keeps accumulating until it gets that ridiculously long string you received.

Try convert = i;

The << operator inserts all 'i's to the stream. So at the end you will get all the numbers yo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top