プラットフォームに依存しない方法がいくつかあります。stringstream(http://www.cplusplus.com/reference/sstream/stringstream/)
C++ では、多くの<<
演算子のオーバーロードを持つを使用できます。ostream&
そのため、 (not ) への参照をoFstream
出力メソッドに渡すと、ファイル、標準出力ストリーム、および文字列出力を簡単に切り替えることができます。これらのストリームはすべて ostream から継承されるためです。次に、必要に応じてstd::string
オブジェクトをstringstream
取得し、そこから C 文字列を取得できます。
コード例:
出力関数 (またはメソッド。この例の 2 番目の引数は必要ありません):
void PrintMyObjectToSomeStream(std::ostream& stream, const MyClass& obj)
{
stream << obj.pubField1;
stream << obj.pubField2;
stream << obj.GetPrivField1();
stream << "string literal";
stream << obj.GetPrivField2();
}
使用法:
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
または、オーバーロードできますoperator<<
:
std::ostream& operator<<(std::ostream& stream, const MyClass& obj)
{
stream << obj1.pubField;
//...and so on
return stream;
}
次に、次のように使用できます。
MyClass obj2;
int foo=100500;
std::stringstream sstr2;
std::ofstream ofs;//don't forget to open it
//print to stringstream
sstr2 << obj2 << foo << "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 << obj2 << foo << "string lineral followed by int\n";
使用はC++よりもCですが、アントンの答えFILE
を切り替える方法や使用する方法を考えることができますfpirntf
。sprintf