In my code there is a loop that adds sth like that "number," to stringstream. When it ends, I need to extract ',' add '}' and add '{' if the loop is to repeated.
I thought i can use ignore() to remove ',' but it didn't work. Do you know how I can do what I describe?
example:
douCoh << '{';
for(unsigned int i=0;i<dataSize;i++)
if(v[i].test) douCoh << i+1 << ',';
douCoh.get(); douCoh << '}';
I've found this way using
pop_back()
string's method since c++11. Probably not so good as smarter ones above, but useful in much more complicated cases and/or for lazy people.You can extract the string (with the
str()
member), remove the last char withstd::string::erase
and then reset the new string as buffer to thestd::ostringstream
.However, a better solution would be to not insert the superfluous
','
in the first place, by doing something like that :You can seek the
stringstream
and go back 1 character, usingstringstream::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}
.You could use
std::string::erase
to remove the last character directly from the underlying string.I have had this very problem and I found out that you can simply do:
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.