user2710184
user2710184

Reputation: 347

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? (provided of course I've opened the file and all that stuff).

Upvotes: 0

Views: 99

Answers (2)

Will Custode
Will Custode

Reputation: 4594

Using fstream works just like cin and 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.

Upvotes: 1

john
john

Reputation: 87959

Yes just give it an ostream& parameter

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

becomes

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

Upvotes: 3

Related Questions