简体   繁体   English

在文件流中打开简单函数C ++

[英]Opening a simple function in a file stream c++

If I have a simple function that prints to standard output maybe something like an integer or lets say a string like "Flipy flops", then is there a way to call the same function but instead of printing to standard output it prints the string "Flipy flops" to a file stream? 如果我有一个简单的函数可以打印到标准输出,例如整数或可以说是“ Flipy flops”之类的字符串,那么有一种方法可以调用相同的函数,但是它不是打印到标准输出,而是打印字符串“ Flipy”失败”到文件流? (provided of course I've opened the file and all that stuff). (当然,前提是我已经打开了文件和所有东西)。

Yes just give it an ostream& parameter 是的,只给它一个ostream&参数

void my_function(...)
{
    cout << ...
}

becomes

void my_function(ostream& out, ...)
{
    out << ...
}

Using fstream works just like cin and cout. 使用fstream就像cin和cout一样。

void SomeMethod( )
{
    ofstream myFile( "myFile.txt" );
    myFile << FlipyFlops( );
    myFile.close( );
}

char* FlipyFlops( )
{
    return "flipy flops"; // or "flippy floppies", whichever you prefer
}

ofstream is for output to a file and ifstream is for reading from a file. ofstream用于输出到文件, ifstream用于从文件读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM