从 stringstream 中删除 char 并附加一些数据
在我的代码中,有一个循环将诸如“数字”之类的东西添加到字符串流中。当它结束时,我需要提取“,”添加“}”并添加“{”(如果要重复循环)。
我以为我可以使用ignore()来删除',',但它不起作用。你知道我怎样才能做到我所描述的吗?
例子:
douCoh << '{';
for(unsigned int i=0;i<dataSize;i++)
if(v[i].test) douCoh << i+1 << ',';
douCoh.get(); douCoh << '}';
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 << '}';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以使用
stringstream::seekp
来查找stringstream
并返回 1 个字符。请注意,它不会删除最后一个字符,而只会移动写入头。在本例中这就足够了,因为我们用}
覆盖最后一个字符。You can seek the
stringstream
and go back 1 character, usingstringstream::seekp
. Note that it does not remove the last character, but only moves the write head. This is sufficient in this case, as we overwrite the last character with an}
.您可以提取字符串(使用
str()
< /a> 成员),使用std::string 删除最后一个字符: :erase
然后将新字符串重置为缓冲区 <代码>std::ostringstream。然而,更好的解决方案是首先不要插入多余的
','
,方法如下:You can extract the string (with the
str()
member), remove the last char withstd::string::erase
and then reset the new string as buffer to thestd::ostringstream
.However, a better solution would be to not insert the superfluous
','
in the first place, by doing something like that :我遇到了这个问题,我发现你可以简单地执行以下操作:
并继续插入数据。正如其他人所说,首先避免插入错误数据可能是理想的解决方案,但就我而言,这是第三方库函数的结果,而且我想避免将数据复制到字符串。
I have had this very problem and I found out that you can simply do:
And the keep inserting data. As others stated, avoiding inserting the bad data in the first place is probably the ideal solution, but in my case was the result of a 3rd party library function, and also I wanted to avoid copying the data to strings.
从 c++11 开始,我就使用
pop_back()
string 的方法找到了这种方法。可能不如上面更聪明的人那么好,但在更复杂的情况和/或对于懒惰的人来说很有用。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.享受 std::copy、迭代器和特征的乐趣。
您要么必须假设您的数据是可反向迭代的(end - 1),要么您的输出可以倒带。
我选择倒带更容易。
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.
您可以使用
std::string::erase
直接从底层字符串中删除最后一个字符。You could use
std::string::erase
to remove the last character directly from the underlying string.为什么不直接检查柜台呢?并且不插入“,”
Why not just check the counter? And not insert the ','