Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove char from stringstream and append some data

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 << '}'; 
like image 981
lord.didger Avatar asked Dec 28 '10 12:12

lord.didger


People also ask

How do I delete a character from Stringstream?

To remove the last character from the string, we will use the seekp() method of the stringstream class.

How do you clean Stringstream?

For clearing the contents of a stringstream , using: m. str("");

What is the difference between string and Stringstream?

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.


2 Answers

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 << '}'; 
like image 142
bcmpinc Avatar answered Oct 14 '22 13:10

bcmpinc


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 << '}'; 
like image 21
Sylvain Defresne Avatar answered Oct 14 '22 13:10

Sylvain Defresne