Logo  

CS256 - Fundamentals of Structured Programming

Displaying exercises/e8/solution/p6.c

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

/**
 * Complete this function to place the text in 'str' on the screen enclosed
 * inside of a "box" drawn with the alternate character set line drawing
 * characters (you may not use a sub-window or any of the curses box drawing
 * functions.)  The upper left corner of the box should be drawn at the y,x
 * coordinate and the box should only be as wide as is needed to display the
 * text (with a space before and after it.)  The function should refresh
 * the screen after the box is drawn.
 */
void mybox(int y, int x, char str[])
{
  // Width of the string + 2 extra for space characters before and after:
  int w = strlen(str)+2;

  // Draws the top line:
  move(y,x);
  addch(ACS_ULCORNER);
  for(int i=0; i < w; i++) addch(ACS_HLINE);
  addch(ACS_URCORNER);
  // Draws the middle line:
  move(y+1,x);
  addch(ACS_VLINE);
  addch(' ');
  printw("%s", str);
  addch(' ');
  addch(ACS_VLINE);
  // Draws the bottom line:
  move(y+2,x);
  addch(ACS_LLCORNER);
  for(int i=0; i < w; i++) addch(ACS_HLINE);
  addch(ACS_LRCORNER);
  refresh();
}


int main(void)
{
  // Do not modify the following code:
  initscr();
  clear();

  mybox(10,10,"Hello there!");
  mybox(15,15,"Hi!");
  mybox(12,30,"Another box");

  /**
   * Print the message "Press any key to exit" in the bottom left corner and
   * wait for a keypress to exit the program.  Do not clear the screen.
   */
  mvprintw(LINES-1, 0, "Press any key to exit");
  refresh();

  getch();
  endwin();
  return 0;
}