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条回答
We Are One
2楼-- · 2019-02-08 11:02

Have fun with std::copy, iterators and traits. You either have to assume that your data is reverse iterable (end - 1) or that your output can be rewinded. I choose it was easier to rewind.

#include <ostream>
#include <algorithm>
#include <iterator>

namespace My
{
  template<typename Iterator>
  void print(std::ostream &out, Iterator begin, Iterator end)
  {
    out << '{';
    if (begin != end) {
      Iterator last = end - 1;
      if (begin != last) {
        std::copy(begin, last, std::ostream_iterator< typename std::iterator_traits<Iterator>::value_type  >(out, ", "));
      }
      out << *last;
    }
    out << '}';
  }
}

#include <iostream>

int main(int argc, char** argv)
{
  My::print(std::cout, &argv[0], &argv[argc]);
  std::cout << '\n';
}
查看更多
Animai°情兽
3楼-- · 2019-02-08 11:02

Why not just check the counter? And not insert the ','

douCoh << '{';
for(unsigned int i=0;i<dataSize;i++){
  if(v[i].test){
    douCoh << i+1;
    if(i != dataSize - 1) douCoh << ',';
  }
}
/*douCoh.get();*/ douCoh << '}';
查看更多
登录 后发表回答