Reputation: 1635
I have a void type function displaying a couple of integers to the console. I want these integers to be written to a file. This is the function I'm talking about:
void inorder(node *root)
{
if(root)
{
inorder(root->left);
std::cout << root->key << " ";
inorder(root->right);
}
}
I'm aware of the fact that it could have been done if I'd return array of integers. But it would complicate my code, I would have to add some kind of a count argument etc.
Is this possible to write the outcome of this function to a file?
Upvotes: 2
Views: 81
Reputation: 227370
You could trivially change the function to take a reference to an std::ostream
, then pass it an ofstream
or std::cout
depending on whether you want to write to a file or to the standard output:
void inorder(node *root, std::ostream& os)
{
if(root)
{
inorder(root->left, os);
os << root->key << " ";
inorder(root->right, os);
}
}
then
node* root = ....;
// write to stdout
inorder(root, std::cout);
// write to a file
std::ofstream myfile("myfile.txt");
inordet(root, myfile);
Upvotes: 3