有几种独立于平台的方法可以做到这一点。在 C++ 中,您可以使用stringstream(http://www.cplusplus.com/reference/sstream/stringstream/)
,它有许多<<
运算符重载。因此,如果您将ostream&
(not oFstream
) 的引用传递给输出方法,您可以轻松地在文件、标准输出流和字符串输出之间切换,因为所有这些流都继承自 ostream。然后,如果需要,您可以从中获取std::string
对象并从中获取 C 字符串。stringstream
代码示例:
输出函数(或方法,则不需要示例中的第二个参数):
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";
使用FILE
C 比 C++ 更多,但您可以考虑如何在fpirntf
和sprintf
或使用 Anton 的答案之间切换。