remove char from stringstream and append some data

后端 未结 9 1496
情深已故
情深已故 2020-12-31 01:42

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.

9条回答
  •  北海茫月
    2020-12-31 02:04

    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 
    #include 
    #include 
    
    namespace My
    {
      template
      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::value_type  >(out, ", "));
          }
          out << *last;
        }
        out << '}';
      }
    }
    
    #include 
    
    int main(int argc, char** argv)
    {
      My::print(std::cout, &argv[0], &argv[argc]);
      std::cout << '\n';
    }
    

提交回复
热议问题