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?
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
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.
Aside of ANSI escape sequences you might wish to investigate 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.
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.
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