remove char from stringstream and append some data

2019-02-08 10:19发布

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 << '}';

8条回答
\"骚年 ilove
2楼-- · 2019-02-08 10:40

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.

douCoh << '{';
for(unsigned int i=0;i<dataSize;i++)
  if(v[i].test) douCoh << i+1 << ',';

string foo(douCoh.str());
foo.pop_back();
douCoh.str(foo);
douCoh.seekp (0, douCoh.end);  

douCoh << '}';
查看更多
再贱就再见
3楼-- · 2019-02-08 10:45

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 << '}';
查看更多
Root(大扎)
4楼-- · 2019-02-08 10:45
stringstream douCoh;
for(unsigned int i=0;i<dataSize;i++)
  if(v[i].test)
    douCoh << ( douCoh.tellp()==0 ? '{' : ',' ) << i+1;
douCoh << '}';
查看更多
走好不送
5楼-- · 2019-02-08 10:57

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 << '}';
查看更多
对你真心纯属浪费
6楼-- · 2019-02-08 10:57

You could use std::string::erase to remove the last character directly from the underlying string.

查看更多
家丑人穷心不美
7楼-- · 2019-02-08 11:02

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.

查看更多
登录 后发表回答