remove char from stringstream and append some data
stringstream douCoh;
for(unsigned int i=0;i<dataSize;i++)
if(v[i].test)
douCoh << ( douCoh.tellp()==0 ? '{' : ',' ) << i+1;
douCoh << '}';
You can seek the stringstream
and go back 1 character, using stringstream::seekp
. Note that it does not remove the last character, but only moves the write head. This is sufficient in this case, as we overwrite the last character with an }
.
douCoh << '{';
for(unsigned int i=0;i<dataSize;i++)
if(v[i].test) douCoh << i+1 << ',';
douCoh.seekp(-1,douCoh.cur); douCoh << '}';
You can extract the string (with the str()
member), remove the last char with std::string::erase
and then reset the new string as buffer to the std::ostringstream
.
However, a better solution would be to not insert the superfluous ','
in the first place, by doing something like that :
std::ostringstream douCoh;
const char* separator = "";
douCoh << '{';
for (size_t i = 0; i < dataSize; ++ i)
{
if (v[i].test)
{
douCoh << separator << i + 1;
separator = ",";
}
}
douCoh << '}';
I have had this very problem and I found out that you can simply do:
douCoh.seekp(-1, std::ios_base::end);
And the keep inserting data. As others stated, avoiding inserting the bad data in the first place is probably the ideal solution, but in my case was the result of a 3rd party library function, and also I wanted to avoid copying the data to strings.