Int to String Conversion in Loop

I'm writing a program in which I have to concatenate an item name and item number. To do this I have written the following function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string catNameNum (InventoryReport ary[])
{
    string str, numStr;
    ostringstream convert;
    
    for (int i = 0; i < NUM; i++)
    {
        
        convert << ary[i].itemNum;
        
        numStr = convert.str();
        
        cout << numStr << endl;             //TEST
        str = ary[i].itemName + numStr;
        
        //cout << str << endl;                //TEST
    }


The issue I have is with my conversion. The string variable numStr seems to be concatenating with the next item number each time. I'm not that familiar with this conversion method, so it may be my lack of understanding of it. I was hoping someone could tell me why it is doing this and suggest how to fix it.

Here is the output for cout << numStr << endl;:

3310
33101090
331010908100
3310109081003390
33101090810033906190
331010908100339061901360
3310109081003390619013609561
33101090810033906190136095616571
331010908100339061901360956165715211
3310109081003390619013609561657152119651
33101090810033906190136095616571521196517381
and so on...
convert << ary[i].itemNum;
This line means "add ary[i].itemNum" to whatever is already in the stringstream, so you're right in that it concatenates with what's already in the buffer. Just do this:
1
2
convert.str(""); //clear previous item number
convert << ary[i].itemNum; //proceed as usual 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string catNameNum (InventoryReport ary[])
{
    string str, numStr;
    // ostringstream convert; // *****
    
    for (int i = 0; i < NUM; i++)
    {
        
        ostringstream convert; // ******
        convert << ary[i].itemNum;
        
        numStr = convert.str();
        
        cout << numStr << endl;             //TEST
        str = ary[i].itemName + numStr;
        
        //cout << str << endl;                //TEST
    }


Simpler:
1
2
3
4
5
string catNameNum (InventoryReport ary[])
{
    for (int i = 0; i < NUM; i++)
        str = ary[i].itemName + std::to_string(i) ;
}
Thanks @Keene. That's what I had in mind, just didn't know how.
Topic archived. No new replies allowed.