The Allegro Wiki is migrating to github at

Reading a string from the keyboard

From Allegro Wiki
Jump to: navigation, search

One way of reading a string from the keyboard, using Allegro and C, in graphics mode.

How it works:

The function read_string(char *str_to, int size) takes as parameters a char array and the size of it.

In that array it will store the string the user inputs.

It will clean the string with \0 on start.

Then it will wait for user input until ENTER is pressed.

When the user press a letter key, it will put the char in the string.

The main() shows how to call this simple function.

Note that this is a very simple demo on a basic way to read a string in graphics mode, you will need to customize it to suit your needs. Also, customize the redraw function to use something better than just clearing the screen (it will flicker), for example, use double buffer, or dirty rectangles method.

<highlightSyntax language="c"> // Little example - By Kronoman - Taking a string from keyboard

  1. include <allegro.h>

void read_string(char *str_to, int size) {

       int cur_pos = 0; // position of caret
       int the_key = 0;
       int i;
       for (i = 0; i < size; i++)
               str_to[i] = '\0'; // 'clean' the string

       while (the_key>>8 != KEY_ENTER)
               the_key = readkey();
               if ((the_key & 0xff) >= ' ') // get only valid chars
                       str_to[cur_pos] = the_key & 0xff;
                       if (cur_pos > size-2) cur_pos = size-2;
               if (the_key >> 8 == KEY_BACKSPACE)
                       str_to[cur_pos] = '\0'; // chop the string
                       cur_pos --;
                       if (cur_pos < 0) cur_pos = 0;
               // lame redraw (use double buffer, whatever)
               textout(screen,font, str_to, 0,0, makecol(255,255,255));


int main() {

       char my_str[40]; // the buffer to read into
       // init allegro and graphics mode

       read_string(my_str, 40); // call the function to read a string
       return 0;

} END_OF_MAIN(); </highlightSyntax>