How could I achieve gotoxy() in gcc

淺唱寂寞╮ 提交于 2019-11-27 02:56:03

问题


I am using gcc in ubuntu.so, I compile and execute in terminal. But In a online programming contest, they require the output as shown in diagram.

For that, if I use TURBOC I can get it using conio.h using gotoxy() to get spiral format of output. But in Ubuntu , How could I achieve this?


回答1:


Use the ncurses library.

Here's an example, adapted from http://www.paulgriffiths.net/program/c/srcs/curhellosrc.html

#include <stdlib.h>
#include <stdio.h>
#include <curses.h>

int main(void) {
    WINDOW * mainwin;

    /*  Initialize ncurses  */

    if ( (mainwin = initscr()) == NULL ) {
        fprintf(stderr, "Error initialising ncurses.\n");
        exit(EXIT_FAILURE);
    }

    move(10, 15);
    addch('X');
    refresh();

    getch();

    delwin(mainwin);
    endwin();
    refresh();

    return EXIT_SUCCESS;
}

Further information is available here: http://invisible-island.net/ncurses/ncurses-intro.html#stdscr




回答2:


Assuming because it is a contest and they don't want dependencies like ncurses you could try to do it in memory.

Set up 2 dimensional array of char - lines and columns - say 24x80. Write your own version of gotoxy() which assigns values into the proper cells. When done plotting, print out the array of lines.




回答3:


Aside of ANSI escape sequences you might wish to investigate ncurses:

http://www.gnu.org/s/ncurses/

It all ultimately depends upon the capabilities of the terminal running the program, not the actual host, language, or library. Consider what happens redirecting program output to a file or to a printer.

conio.h API is more to do with a fixed console, with Unix like systems you usual deal with terminals which can be more varied such as resizable X-Terminals.




回答4:


Determine how many lines of output you need. Allocate an array of "char *" with one entry per line of output needed. When you place a number use "realloc()" to increase the size of the line and fill from the old end to the new end with spaces (if necessary); then put your number at the right place in that line (in memory).

After you've build an array of string in memory; do a for loop that prints each line (and frees the memory you allocated).

You don't need "gotoxy()" or anything to control cursor position.




回答5:


Since it isn't here yet, I just wanted to say about an example using ANSI escape sequences as Steve-o mentioned.

void gotoxy(int x, int y)
{
    printf("%c[%d;%df", 0x1B, y, x);
}

I got it from here.

0x1B is hexadecimal for 27 in decimal and is the ASCII for ESC. The escape sequences start with it

%m;%nf moves the cursor to row n, column m.

The ANSI escape sequences are used "to control the formatting, color, and other output options on video text terminals"



来源:https://stackoverflow.com/questions/7170021/how-could-i-achieve-gotoxy-in-gcc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!