从stringstream中删除char并附加一些数据 [英] remove char from stringstream and append some data

查看:51
本文介绍了从stringstream中删除char并附加一些数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,有一个循环,将诸如数字之类的东西添加到stringstream中。当结束时,我需要提取','添加'}'并添加'{'(如果要重复循环)。

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.

我以为我可以使用ignore()删除',',但是没有用。

I thought i can use ignore() to remove ',' but it didn't work. Do you know how I can do what I describe?

示例:

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


推荐答案

您可以提取字符串(使用 str() 成员) ,请使用 std :: string :: erase删除最后一个字符 ,然后将新字符串重置为 std :: ostringstream

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

这篇关于从stringstream中删除char并附加一些数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆