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 << '}';
To remove the last character from the string, we will use the seekp() method of the stringstream class.
For clearing the contents of a stringstream , using: m. str("");
Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.
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 << '}';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With