1

I am facing a problem with the below code.

short int decrypted0[] = {0,2};
string message = "22";
string string0 ="";

for(i=0;i<message.size();i++)
{        
     ss<<decrypted0[i];
     string0+=ss.str();     
}

Why does after the second iteration string0 have a value "002" rather than "02"?

I tried with VS and Qt, Same results.

Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68

1 Answers1

2

std::stringstream::str() does not empty the stream, it's more of a snapshot of the current internals. The clear its internal buffer use ss.str("").

This means that your loop gives after the first iteration:

    ss.str() == "0"
    string0 == "0"

and then the after the second iteration you get:

    ss.str() == "02"
    string0 == "002"

Much easier would be to do:

    for(i=0;i<message.size();i++)
         ss<<decrypted0[i];
    string0 = ss.str();
SirGuy
  • 10,660
  • 2
  • 36
  • 66