Search code examples
c++fileterminalcygwinbackspace

Code that can output changing number to both terminal and file


I have a c++ program which writes changing numbers to screen, something in the vein of the following snippet:

    stringstream ss, ssd; ss << 0; int decs=0; ssd << decs;

    cout << "Number ";

    for(int i=1;i<=1000;i++) {

        cout << ss.str() << "   Decades: " << decs; cout.flush();

        int l=ss.str().length()+12+ssd.str().length(); 
        for(int j=0;j<l;j++) cout << "\b";

        this_thread::sleep_for (chrono::milliseconds(100));

        ss.str(""); ss << i;

        if(i%10==0) {
            decs++; ssd.str(""); ssd << decs;
        }

    }

This works fine, but sometimes (not always) I would like to send the output to a file instead of the terminal, using e.g. ./prog > out.txt. Here the backspace character \b doesn't delete character but outputs some symbol (googling tells me this is not surprising).

One option would be to e.g. only output the data at the end of the calculation when printing to a file. But this would entail different code for terminal/file, switching with an input parameter for example. Is there a way I can do this without having separate code for terminal/file output?

I am using cygwin on Windows 7.


Solution

  • A possible workaround may be to use std::cerr for intermediate result (and so for '\b'),

    and std::cout for final result.