views:

69

answers:

1

I'm writing a code to output fibonacci series in C++, which is simple enough, but since I'm new to programming, I'm considering ways to control

I was wondering if there's a way to control time for when outputs come out without processing time being included (e.g. If it takes .0005 seconds to process my input and I want it to repeat the output in 1 second rather than 1.0005 seconds).

I also am wondering if there's a way to just have it output (say 1) and then have it wait for me to press enter, which will make it output the second part (2).

Also, I'd appreciate any other suggestions on how to control output.

+2  A: 

If you're on Windows, a quick way to pause is to call system("pause"); This isn't a very professional way of doing things, however.

A way to pause with the std namespace would be something like this:

cout << "Press Enter to continue . . ." << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');

As for your main question... If you're just dealing with text output to the user, it's not possible for them to notice a five microsecond delay. They can notice if your interval lengths fluctuate by tens of milliseconds, however. This is why sleep(..) functions sometimes fail.

Let's take your example of wanting to output another number in the Fibonacci sequence once per second. This will work just fine:

#include <ctime>
#include <limits>
#include <iostream>

void pause() {
    std::cout << "Press Enter to continue . . ." << std::endl;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

int main() {
    clock_t next = clock();
    int prev1, prev2, cur = 0;

    for (int i = 0; i < 47; ++i) {
        if (i < 2) cur = i;
        else cur = prev1 + prev2;
        prev2 = prev1;
        prev1 = cur;

        while (next > clock());
        std::cout << (i+1) << ": " << cur << std::endl;
        next += CLOCKS_PER_SEC;
    }

    pause();
    return 0;
}

The next number in the sequence is computed and ready to print prior to the wait, thus the computation time will not add any delay to the timed output.

If you want your program to continue outputting at a fixed rate while your program works in the background, you'll need to look into threads. You can have your results added to a queue in one thread, while another thread checks for results to print once per second.

Gunslinger47
+1 for mentioning threads - I was going to do that until I noticed you had already.
Cam