You are calling recur
before log
is closed in it's deconstructor. This means the file will be opened by multiple ofstream
s at once, and the ofstream
s earlier in the recursion do not get flushed as celtschk pointed out. It should work if you close the file before calling recur
. It works if you declare log
as static
because then log only gets constructed once and therefore opened once. The code below adds a block to make sure log
's deconstructor is called before recur
is.
int recur(int num)
{
static unsigned count = 0;
{
std::ofstream log("log.txt",std::ios_base::app|std::ios_base::out);
std::cout << count << "\n";
log << count << "\n";
++count;
}
if (num==0) return 0;
num += recur(num -1);
return num;
}