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