remove char from stringstream and append some data

后端 未结 9 1445
情深已故
情深已故 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:08

    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 << '}';
    
    0 讨论(0)
  • 2020-12-31 02:10

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

    0 讨论(0)
  • 2020-12-31 02:13

    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 << '}';
    
    0 讨论(0)
提交回复
热议问题