C Shell Buffer

ShortYute 0 Tallied Votes 203 Views Share

Modified mostly from dileepkumar235's Login functionality in C-language

Inspiration from Narue and my previous post (Limit buffer Input )

This allows you to prevents the user from entering past the array limit (SizeOfArray) if the user enters more the curser will just automatically
backspace by 1 for eg (max is 5) "eifje|" -> ""eifj|" and will terminate the array when enter is inputed.

(If your using Visuall C++ include <conio.h>
and change
getch to _getch )

All others include <conio.h>

My compiler is Code Blocks SVN 6202 (Self Built)
Note: I didn't see any reason to return anything... post suggestions please... Thank you :) (I also have a double version that prevents the user from entering any alpha char... if requested I will post it...)

So if you want you can use it like this this:

string = malloc (SIZE_A);
ShellBufString ( string, SIZE_A );
printf ( "The string you entered is [%s]", string )/* Do stuff */
free ( string );

void ShellBufString ( char *str, const int SizeOfArray ) {

    int i;
    char ch = 'a';/*dummy character in ch */

    for ( i = 0; i < SizeOfArray; ) {

        ch = getch();

        if ( ch == 13 ) {
            break;
        }
        else if ( ch == 8 ){
            if( i != 0 ) { /*this is for avoiding the ENTER instructions getting deleted */

                printf( "\b" );  /*printing backspace to move cursor 1 pos back*/
                printf( "%c", 32 );/*making the char invisible which is already on console*/
                printf( "\b" ); /*printing backspace to move cursor 1 pos back*/
                i--;
                str[ i ] = '\0';
            }
            else {
                continue;
            }

        }
        else if ( ch == 0 || ch == -32 || ch == 27 || ch == 9 ) {
            /* f1 to f12 Insert home etc., arrow keys, esc,  tab */
            ch = getch ();
            continue;
        }
        else if ( i == SizeOfArray - 1  ) {
            printf( "\b" );  /*printing backspace to move cursor 1 pos back*/
            printf( "%c", 32 );/*making the char invisible which is already on console*/
            printf( "\b" ); /*printing backspace to move cursor 1 pos back*/
            i--;
        }
        else {
            putchar( ch );/* char will be printed instead of the character */
            str[ i ] = ch;
            i++;
        }
    }
    str[ i ] = '\0'; /* Add null terminator */


    printf ( "\n" ); /* Simulate the user pressing enter */

}