Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are several platform-independent ways to do it. In C++ you can use <code>stringstream(http://www.cplusplus.com/reference/sstream/stringstream/)</code>, which has many <code>&lt;&lt;</code> operator overloads. So if you pass a reference to <code>ostream&amp;</code> (not <code>oFstream</code>) to the output method, you can easily switch between files, stadard output stream and string outputs, because all this streams are inherited from ostream. Then you can get <code>std::string</code> object from <code>stringstream</code> and get C-string from it if you need.</p> <p>Code example:</p> <p>Output function (or method, then you don't need the second argument from the example):</p> <pre class="lang-cpp prettyprint-override"><code>void PrintMyObjectToSomeStream(std::ostream&amp; stream, const MyClass&amp; obj) { stream &lt;&lt; obj.pubField1; stream &lt;&lt; obj.pubField2; stream &lt;&lt; obj.GetPrivField1(); stream &lt;&lt; "string literal"; stream &lt;&lt; obj.GetPrivField2(); } </code></pre> <p>Usage:</p> <pre class="lang-cpp prettyprint-override"><code>MyClass obj1; std::ofsstream ofs; std::stringstream sstr; //...open file for ofs, check if it is opened and so on... //...use obj1, fill it's member fields with actual information... PrintMyObjectToSomeStream(obj1,std::cout);//print to console PrintMyObjectToSomeStream(obj1,sstr);//print to stringstream PrintMyObjectToSomeStream(obj1,ofs);//print to file std::string str1=sstr.str();//get std::string from stringstream char* sptr1=sstr.str().c_str();//get pointer to C-string from stringstream </code></pre> <p>Or you can overload <code>operator&lt;&lt;</code>:</p> <pre class="lang-cpp prettyprint-override"><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, const MyClass&amp; obj) { stream &lt;&lt; obj1.pubField; //...and so on return stream; } </code></pre> <p>then you can use it in this way:</p> <pre class="lang-cpp prettyprint-override"><code>MyClass obj2; int foo=100500; std::stringstream sstr2; std::ofstream ofs;//don't forget to open it //print to stringstream sstr2 &lt;&lt; obj2 &lt;&lt; foo &lt;&lt; "string lineral followed by int\n"; //here you can get std::string or char* as like as in previous example //print to file in the same way ofs &lt;&lt; obj2 &lt;&lt; foo &lt;&lt; "string lineral followed by int\n"; </code></pre> <p>Using <code>FILE</code> is more C than C++ but you can think how to switch between <code>fpirntf</code> and <code>sprintf</code> or use Anton's answer.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload