Pregunta

Given codes as below:

int recur(int num);
int main()
{
    recur(5);
    return 0;
}    

int recur(int num)
{
    static unsigned count = 0;        
    //static
            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;
}

Output from std::cout :

0
1
2
3
4
5

Content of log.txt:

5
4
3
2
1
0

Why was it like so?

I tried to put static before std::ofstream just as commented in the function recur. Then it worked fine, exactly the same as the output from std::cout. Can anyone explain the rationale under hood?

¿Fue útil?

Solución

You are calling recur before log is closed in it's deconstructor. This means the file will be opened by multiple ofstreams at once, and the ofstreams 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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top