简体   繁体   中英

How do I save number of columns in Terminal with C++ to a variable?

I've been searching quite a lot, and all I've had are answers for C, not C++. I'm using Linux, so I won't be able to use windows.h

What I need to do is get the number of columns in the terminal window it's running, then print something in the middle with ncurses. How can I achieve this?

Here is how :

int columns=system("tput cols");

You need to #include<stdlib.h> . Then you can use mvprintw(y, x, "your text here") ; to print text wherever you want.

Note tput lines gives the number of rows, in case you want it too.

Note that i am ignoring the line I've been searching quite a lot, and all I've had are answers for C, not C++. . This is (one way of) how you do it, C or C++ . You may refer to this as an example.

If you're going to be using ncurses, just use the facility (section 6.3.4) that exists in the library to do it:

int main(void) {
    int rows, cols;

    initscr();
    getmaxyx(stdscr, rows, cols); // you now have the max for both axis
}

It's important to note that you should be refreshing these values (and the screen) upon receiving a SIGWINCH signal, or your windows will look rather odd if someone changes the height or width of their terminal program.

There is no C++ version of ncurses because it's not needed, but many prefer to create their own wrapper around it to get easier access to the functionality they want in the context of their application. The ncurses.h header will check to see if C++ is being used, and adjust accordingly:

#ifdef __cplusplus
extern "C" {

To use it, simply link it and use it procedurally, or use it in whatever class you have dealing with terminal I/O in your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM