[英]remove char from stringstream and append some data
在我的代碼中有一個循環,它將“number”添加到stringstream。 當它結束時,我需要提取','添加'}'並添加'{'如果要重復循環。
我以為我可以使用ignore()刪除','但它不起作用。 你知道我怎么做我描述的嗎?
例:
douCoh << '{';
for(unsigned int i=0;i<dataSize;i++)
if(v[i].test) douCoh << i+1 << ',';
douCoh.get(); douCoh << '}';
您可以提取字符串(使用str()
成員),使用std::string::erase
刪除最后一個char,然后將新字符串作為緩沖區重置為std::ostringstream
。
但是,一個更好的解決方案是首先不要插入多余的','
,做類似的事情:
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
,回去1個字符,使用stringstream::seekp
。 請注意,它不會刪除最后一個字符,而只會移動寫頭。 在這種情況下,這就足夠了,因為我們用}
覆蓋最后一個字符。
douCoh << '{';
for(unsigned int i=0;i<dataSize;i++)
if(v[i].test) douCoh << i+1 << ',';
douCoh.seekp(-1,douCoh.cur); douCoh << '}';
我遇到了這個問題,我發現你可以做到:
douCoh.seekp(-1, std::ios_base::end);
並保持插入數據。 正如其他人所說,避免首先插入壞數據可能是理想的解決方案,但在我的情況下是第三方庫函數的結果,我也想避免將數據復制到字符串。
stringstream douCoh;
for(unsigned int i=0;i<dataSize;i++)
if(v[i].test)
douCoh << ( douCoh.tellp()==0 ? '{' : ',' ) << i+1;
douCoh << '}';
我從c ++ 11開始就使用pop_back()
字符串的方法找到了這種方法。 可能不如上面那些更聰明的那么好,但在更復雜的情況下和/或對於懶惰的人來說是有用的。
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 << '}';
享受std :: copy,iterators和traits的樂趣。 您要么必須假設您的數據是可反向迭代的(結束-1),要么可以重新輸出您的輸出。 我選擇它更容易倒帶。
#include <ostream>
#include <algorithm>
#include <iterator>
namespace My
{
template<typename Iterator>
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<Iterator>::value_type >(out, ", "));
}
out << *last;
}
out << '}';
}
}
#include <iostream>
int main(int argc, char** argv)
{
My::print(std::cout, &argv[0], &argv[argc]);
std::cout << '\n';
}
您可以使用std::string::erase
直接從基礎字符串中刪除最后一個字符。
為什么不檢查櫃台? 而不是插入','
douCoh << '{';
for(unsigned int i=0;i<dataSize;i++){
if(v[i].test){
douCoh << i+1;
if(i != dataSize - 1) douCoh << ',';
}
}
/*douCoh.get();*/ douCoh << '}';
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>
template<typename T>
std::string implode(std::vector<T> vec, std::string&& delim)
{
std::stringstream ss;
std::copy(vec.begin(), vec.end(), std::ostream_iterator<std::string>(ss, delim.c_str()));
if (!vec.empty()) {
ss.seekp(-1*delim.size(), std::ios_base::end);
ss<<'\0';
}
return ss.str();
}
int main()
{
std::cout<<implode(std::vector<std::string>{"1", "2", "3"}, ", ");
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.