Search code examples
c++ostringstream

How to manage 'ostringstream' object in C++?


This is a snippet of code from C++ program.

string TwoSeries::getArrays()
{
    ostringstream outIndex;
    ostringstream outValueA;
    ostringstream outValueB;
    string stA;
    string stB;
    string valueA;
    string index;
    int *arA;
    int * arB;
    string valueB;
    for(int x = 0; x < 200; x++)  
    {         

        outIndex << x;
        index = outIndex.str();



         arA = getArrayA();
        outValueA << *(arA + x);
        valueA = outValueA.str();


          arB = getArrayB();
        outValueB << *(arB + x);
        valueB = outValueB.str();


        stA += index + ":" + valueA + " ";
        stB += index + ":" + valueB + " ";

    }

   // return "Series A: \n"+stA+ "\n"+"Series B: \n"+ stB;   
    return index;
}

This function should return the last index converted from int into string, and that should be 199. But instead this object 'outIndex' concatenates all the digits (strings) into one string and gives as the result something like this: 1234567891011121314151617 ... 198199. And definitely the last number is 199. And what to force the function after full loop to output only the last number instead all the numbers it has come across. How to do this?


Solution

  • You want to clear the string streams:

    for(int x = 0; x < 200; x++)  
    {         
        outIndex.str("");
        outValueA.str("");
        outValueB.str("");
    

    Alternatively, you can adopt good C++ style and declare them locally in the loop:

    for(int x = 0; x < 200; x++)  
    {         
        ostringstream outIndex;
        ostringstream outValueA;
        ostringstream outValueB;
    

    While you're at it you can move the rest as well. Or... rewrite as follows:

    string TwoSeries::getArrays()
    {
        string index;
    
        int x;
        for(x = 0; x < 200; x++)  
        {         
            ostringstream osA, osB;
    
            osA << x << ":" << *(getArrayA() + x) + " ";
            osB << x << ":" << *(getArrayB() + x) + " ";
    
            string stA = osA.str(); // warning: value isn't used
            string stB = osB.str(); // warning: value isn't used
        }
    
        ostringstream osA, osB;
        outIndex << (x-1); // previous index
        return outIndex.str();
    }
    

    Note that you're doing a lot of redundant work, and right now all those values aren't being used. Perhaps you have more code that you haven't shown :)