Thursday, September 29, 2011

Creating a Menu-Based Text User Interface in ANSI C

The easiest interface one can build (and the most used by console apps) is the Text User Interface. A Text User Interface is usually based on a menu which provides the user with various options.
Below, you have an example of how to implement such a interface using ANSI C:
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

int main(void)
{
    //Variable used for reading the user input
    char option;
    //Variable used for controlling the while loop
    bool isRunning = true;

    while(isRunning==true)
    {
        //Clears the screen
        system("clear");        //For UNIX-based OSes

        //Clears the keyboard buffer
        fflush(stdin);
        //Outputs the options to console
        puts("\n[1]Option1"
             "\n[2]Option2"
             "\n[3]Option3"
             "\n[4]Option4"
             "\n.........."
             "\n[x]Exit");
        //Reads the user's option
        option = getchar();
        //Selects the course of action specified by the option
        switch(option)
        {
            case '1':
                     //TO DO CODE
                     break;
            case '2':
                     //TO DO CODE
                     break;
            case '3':
                     //TO DO CODE
                     break;
            case '4':
                     //TO DO CODE
                     break;
            //...
            case 'x':
                     //Exits the system
                     isRunning = false;
                     return 0;
            default :
                     //User enters wrong input
                     //TO DO CODE
                     break;
        }
    }
    return 0;
}
As you probably observed, this is a general template for a TUI, but you can easily modify it and adapt it to use in your programs.

TIPI used for clearing the console the system("clear") command which works for Unix-based operating systems. If you want to adapt the program for a Windows OS, you should replace the command with system("cls").

Question: In which situations do you prefer creating a text user interface instead of graphical one?

References:
About the TUI

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger