इसे एक नए प्रकार के streambuf
द्वारा हल किया जा सकता है (Standard C++ IOStreams and Locales: Advanced Programmer's Guide and Reference देखें)।
#include <streambuf>
class existing_string_buf : public std::streambuf
{
public:
// Store a pointer to to_append.
explicit existing_string_buf(std::string &to_append);
virtual int_type overflow (int_type c) {
// Push here to the string to_append.
}
};
एक बार जब आप यहाँ विवरण बाहर मांस, आप इसे इस रूप में इस्तेमाल कर सकते हैं:
यह इस प्रकार से देख सकते हैं की एक संक्षिप्त वर्णन है
#include <iostream>
std::string s;
// Create a streambuf of the string s
existing_string_buf b(s);
// Create an ostream with the streambuf
std::ostream o(&b);
अब तुम सिर्फ o
लिखें, और परिणाम s
में संलग्न के रूप में दिखाई देना चाहिए।
// This will append to s
o << 22;
संपादित
@rustyx सही ढंग से नोटों के रूप में, xsputn
अधिभावी प्रदर्शन में सुधार के लिए आवश्यक है।
पूर्ण उदाहरण
निम्नलिखित प्रिंट 22
:
#include <streambuf>
#include <string>
#include <ostream>
#include <iostream>
class existing_string_buf : public std::streambuf
{
public:
// Somehow store a pointer to to_append.
explicit existing_string_buf(std::string &to_append) :
m_to_append(&to_append){}
virtual int_type overflow (int_type c) {
if (c != EOF) {
m_to_append->push_back(c);
}
return c;
}
virtual std::streamsize xsputn (const char* s, std::streamsize n) {
m_to_append->insert(m_to_append->end(), s, s + n);
return n;
}
private:
std::string *m_to_append;
};
int main()
{
std::string s;
existing_string_buf b(s);
std::ostream o(&b);
o << 22;
std::cout << s << std::endl;
}
स्रोत
2016-08-03 20:30:15
मैं http://www.boost.org/doc/libs/1_61_0/doc/html/interprocess/streams.html – bobah
की ओर देखता हूं शायद 'std :: string x :: repr()' या इसी तरह लागू करें , और कॉल करें कि 'एपेंड' और 'ऑपरेटर <<' दोनों में? आदर्श नहीं है, लेकिन आप मध्यवर्ती 'स्ट्रिंगस्ट्रीम' से बचें। – Praetorian
बस 's.append (std :: string :: to_string (x)) के बारे में क्या;'? क्या मुझे कुछ जरूरी याद आया? –