Search code examples
c++consoleconsole-applicationiostreamcout

How to print page by page with cout in C++?


Imagine I have this code:

for (int i=0; i<1000; i++) {
    cout << i << endl;
}

So in the console, we see the result is printed once until 999. We can not see the first numbers anymore (let say from 0 to 10 or 20), even we scroll up.

enter image description here

How can I print output page by page? I mean, for example if there are 40 lines per page, then in the console we see 0->39, and when we press Enter, the next 40 numbers will be shown (40->79), and so on, until the last number.


Solution

  • You could use the % (remainder) operator:

    for (int i=0; i<1000; i++) {
        std::cout << i << '\n';
        if(i % 40 == 39) {
            std::cout << "Press return>";
            std::getchar();
        }
    }
    

    This will print lines 0-39, then 40-79 etc.

    If you need something that figures out how many lines the terminal has and adapts to that, you could use curses, ncurses or pdcurses. For windows, (I think) pdcurses is what you should go for.

    #include <curses.h>
    
    #include <iostream>
    
    int main() {
        initscr();         // init curses
        int Lines = LINES; // fetch number of lines in the terminal
        endwin();          // end curses
    
        for(int i = 0; i < 1000; i++) {
            std::cout << i << '\n';
            if(i % Lines == Lines - 1) {
                std::cout << "Press return>";
                std::getchar();
            }
        }
    }
    

    This only initializes curses, fetches the number of lines in the terminal and then deinit curses. If you want, you could stay in curses-mode and use the curses functions to read and write to the terminal instead. That would give you control over the cursor position and attributes of what you print on screen, like colors and underlining etc.