trangan
trangan

Reputation: 361

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.

Upvotes: 0

Views: 707

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117128

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.

Upvotes: 0

QuentinC
QuentinC

Reputation: 14687

While the previously answers are technically correct, you can only break output at a fixed number of lines, i.e. at least with standard C++ library only, you have no way to know how many lines you can print before filling the entire screen. You will need to resort to specific OS APIs to know that.

UNIX people may tell you that, in fact, you shouldn't bother about that in your own program. If you want to paginate, you should just pipe the output to commands such as less or more, or redirect it to a file and then look at the file with a text editor.

Upvotes: 1

Related Questions