Skip to content

3.2. Handling user text input

N•I•L edited this page Nov 24, 2021 · 3 revisions

Main source: keyboard stdin.

Initializing keyboard

Now that we know how to print text on the DS console, let's do a short talk about scanf (actually, iscanf). It allows user to type text into the program. You'll ask how, as the DS doesn't have a keyboard. Well, you need to create a keyboard instance from libnds:

Keyboard *keyboard = keyboardDemoInit();

iscanf()

Now if you call iscanf("%s",a_var) (or scanf(), see printf vs iprintf discussion) a keyboard pops up.

Check the following code:

// init keyboard
Keyboard *kbd = keyboardDemoInit(); 
char text[256];
// keyboard appears, waits and captures user input until Rtrn is pressed,
// BUT chars don't appear on the screen at the moment of typing
iscanf("Type something: %s", text); 

// writes the user given message
iprintf("You typed %s",text);

// BUT chars don't appear on the screen at the moment of typing

This is because there is nothing in code that tells devkitARM to do this particular thing. Fortunately, Keyboard features a key pressed event handler, so we can do the following:

void OnKeyPressed(int key)
{
   if(key > 0)
      iprintf("%c", key);
}

// and inside main block...
kbd->OnKeyPressed = OnKeyPressed;

Now we can enjoy a full fledged text I/O on our DS.

However, this is pretty impractical in a real game. Even if we need text input in our game, most likely we'll need writing our own custom stylish keyboard implementation.