Writing to a file
Hey guys. I have a problem with writing to a file.
I will try and simplify the problem so it might sound strange.
Lets say I have a function which works out a series of numbers, once each number is found I call another function (say, printnumber). This function writes the number to the output file.
My problem is, the output file seems to only display the last number. I think this is because in the print function i have a piece of code like this
This would sort of over-write the file would it not.
My question is, is there any simple way around this? I have thought about perhaps opening the file only once - outside the first function, but I am unsure how I would send the output file as a function parameter.
Also, another quick question if I may. Say I have two command line parameters (file names). In main, how would I go about doing this :
Couldn't you open the file just once and just write the numbers there?
Otherwise you might open the file for appending.
You might also post code.
You can pass an ofstream via a const reference (that is,
And I think your command-line arguments are going to be in argv and argv.
void printnumber(int number, const ofstream& output)
It doesn't make sense to make the ofstream a reference to const, since you write to an ofstream and you can't do that if it is const. A plain reference is more appropriate.