Search code examples
cturbo-c

Input text in graphics in C programming


I am making a project in C. Its simple, just a Hangman Game.

Got the logic already cause I've done that only in console.

Now, I'm trying to do it in C again with GRAPHICS. I am using Turbo C.

I've read some of the functions of graphics.h: so far I've seen outtext() / outtextxy() something like that. It can print a string.

Can you input a char or string in graphics? Searched a lot but seen nothing. Seen only drawing shapes examples.

How do you input characters, integers etc. in the graphics mode?


Solution

  • From memory, while you can use regular stdio functions printf, scanf, and gets, the graphics driver will paint them over your screen onto a "virtual cursor" position and scroll the screen when it reaches the bottom. You can use the nonstandard conio.h functions such as gotoxy and attempt to position the cursor, but it's still a mediocre way of inputting text, messing up the graphics stuff. You also cannot use the fancy fonts!

    So use getch to read characters without showing them; update a string buffer (manually handling special keys such as Backspace and Return), and draw that on the screen using a font of your choice.

    A short sample snippet of code to get you started:

    #define MAX_INPUT_LEN 80
    
    char inputbuf[MAX_INPUT_LEN];
    int input_pos = 0;
    

    then, in your main loop

    int the_end = 0;
    do
    {
       outtextxy (0,0, inputbuf);
       c = getch();
       switch (c)
       {
            case 8: /* backspace */
              if (input_pos)
              {
                 input_pos--;
                 inputbuf[input_pos] = 0;
              }
              break;
            case 13: /* return */
              the_end = 1;
              break;
            case 27: /* Escape = Abort */
              inputbuf[0] = 0;
              the_end = 1;
              break;
            default:
              if (input_pos < MAX_INPUT_LEN-1 && c >= ' ' && c <= '~')
              {
                 inputbuf[input_pos] = c;
                 input_pos++;
                 inputbuf[input_pos] = 0;
              }
       }
    } while (!the_end);
    

    Before you draw the text, make sure to erase the previous line! I left that out because it's been too long ago I used Turbo-C.