Thread: Limiting the number of characters typed

  1. #1
    Registered User johnnyd's Avatar
    Join Date
    Mar 2002
    Posts
    70

    Lightbulb Limiting the number of characters typed

    Gentle people,

    How does one limit the number of characters that a user can type when using either gets or scanf?
    Excuse me, while I water my money tree.

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    42
    Use fgets.

    Code:
    #define MAX_INPUT = 100  //whatever you like
    
    char buffer[MAX_INPUT + 1];
    fgets(buffer, MAX_INPUT, stdin);
    This is a much easier way to do it.
    http://www.KBeutler.com

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >How does one limit the number of characters that a user can
    >type when using either gets or scanf?
    With gets, you don't. That's why it's so horrible. With scanf you can, but it's not very practical since the limit must be a constant integer:
    scanf ( "%10c", array );

    This method is also very buggy and difficult to get working correctly, it's much better to use fgets instead.

    -Prelude
    My best code is written with the delete key.

  4. #4
    Registered User johnnyd's Avatar
    Join Date
    Mar 2002
    Posts
    70

    I don't think you guys understand...

    Perhaps I wasn't very clear when I first posted this.

    fgets does limit the number of characters captured, but it doesn't limit the number of characters the user can actually type.

    Let me give you an example. I've printed a screen with field graphics etc. When the user types, they can actually overwrite the text that defines the outlimits of the field.

    I want to actually limit the user from typing beyond a certain point on the screen. Beyond that point is graphics that defines the look of the screen.

    So for example the printed output is:

    Employee Name: [ ]

    The user could type:

    Employee Name: [John Jacob Jingleheimer Smith

    and the second brace is over written. Do you understand now? I hope I'm being clear.

    So what I want to do is to stop input when it reaches a certain number of characters, for example:

    Employee Name: [John Jacob Jingleheim]

    and no more...anymore key presses after that amount is ignored. No matter how much is typed, it doesn't go beyond that point.

    THAT'S what I want to accomplish. I've tried some looping structures but they are pretty stupid and don't work.

    I'm wondering if there is a command that can allow you to do that.

    Again, thanks in advance.

    By the way, Prelude, your help so far has been invaluable to helping me understand this language...
    Excuse me, while I water my money tree.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >So what I want to do is to stop input when it reaches a certain
    >number of characters, for example:
    Well, the easiest way to get that kind of functionality would require nonstandard features such as getch and gotoxy. Here's a program that defines it's own gotoxy for Windows systems and uses conio's getch as well as the Windows API function MessageBox. This is just an example, think long and hard before using anything nonstandard.
    Code:
    #include <windows.h>
    #include <stdio.h>
    #include <conio.h>
    #define MAX 20
    #define NEWLINE 0x0D
    
    void gotoxy ( int x, int y )
    {
      COORD coord;
      CONSOLE_CURSOR_INFO c;
      c.dwSize = 20;
      c.bVisible = 0;
      coord.X = (short)x;
      coord.Y = (short)y;
      SetConsoleCursorPosition ( GetStdHandle ( STD_OUTPUT_HANDLE ), coord );
      SetConsoleCursorInfo ( GetStdHandle ( STD_OUTPUT_HANDLE ), &c );
    }
    
    int main ( void )
    {
      char name[MAX];
      int i, j = 16;
      printf ( "Employee Name: [                    ]" );
      gotoxy ( j, 0 );
      for ( i = 0; i < MAX; i++ ) {
        name[i] = (char)getch();
        if ( name[i] == NEWLINE )
          break;
        else
          putchar ( name[i] );
        gotoxy ( ++j, 0 );
      }
      MessageBox ( NULL, "Thank you", "Data Entered", 
                   MB_OK | MB_ICONINFORMATION | MB_SYSTEMMODAL );
      gotoxy ( 0, 1 );
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

  6. #6
    Registered User
    Join Date
    Jan 2002
    Posts
    552
    you need a function that does not wait for the user to type enter before the character is returned, such as getch(). Just create your own function that will get the amount of characters, manually echoing them to screen. Once the max has been reached, just return. This will make it so the control is returned to the calling function immediately after the maximum characters have been inputted, so anything more typed will be received at the next input.

    Code:
    const char *getstring(char *buf, int maxInput, int delim)
    {
        int c;
        char *b = buf;
        for (int i = 0; i < maxInput; i++) {
            c = getch();  // gets a character immediately after it is typed
                                // without echoing
            if (c == EOF || c == delim)
                break;
            *b++ = c;
            putc(c);   // echos the character  
        }
        *b = '\0';
        return buf;
    }
    On second thought, it may not be necessary to use getch, a simple fgetc might work here. The main thing is to use a function that gets a character without waiting for the delimiter to be entered such as gets or scanf

  7. #7
    Unregistered
    Guest
    this is some code Gookin wrote in c for dummies (cant remember which volume). i modified it slightly:

    Code:
    #include <stdio.h>
    #include <conio.h>
    
    #define CR        0x0d  //carriage return
    #define ESC       0x1b  //Escape key
    #define TAB       0x09
    #define LF        0x0a  //line feed
    #define BACKSPACE 0x08
    #define NUL       '\0'  //empty character
    #define QUIT      1
    #define TRUE      1
    #define FALSE     0
    #define LENGTH    15    //size of the string
    
    int input(char *string, int length);
    
    int main(void)
    {
       char string[LENGTH];
    
       printf("Enter string: ");
       if(input(string, LENGTH) == QUIT)
       {
          printf("\n*** Canceled");
          return 0;
       }
       printf("String = %s\n", string);
    
       return 0;
    }
    
    int input(char *string, int length)
    {
       int  done  = FALSE;
       int  index = 0;
       char ch;
    
       string[0] = NUL;
    
       do
       {
          ch = getch();
    
          //check to see whether the buffer is full
          if(index == length)
          {
             switch(ch)
             {
                case ESC:
                   break;
                case CR:
                   break;
                case BACKSPACE:
                   break;
                default:
                   ch = NUL;
             }
          }
    
          //process the keyboard input
          switch(ch)
          {
             case CR:
                putchar(ch);
                putchar(LF);
                string[index] = NUL;
                done = TRUE;
                break;
             case BACKSPACE:
                if(index == 0)
                {
                   break;
                }
                else
                {
                   putchar(ch);
                   putchar(' ');
                   putchar(ch);
                   index--;
                }
                break;
             case ESC:
                return QUIT;
             case NUL:
                break;
             default:        //display & store
                putchar(ch);
                string[index] = ch;
                index++;
           }
       }
       while(!done);
    }
    it comes with a main function to demonstrate how its works. hope you have getch().

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    > comes with a main function to demonstrate how its works.
    > hope you have getch().

    Hell if you're going for un-portable, just combine getch with kbdhit and a counter. Much easier.

    Still, it's hard to beat a single line of code.

    fgets( buf, bufLength, stdin );

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Feb 2002
    Posts
    31
    id rather use fgets, too, but he already explained why he couldnt. fgets may limit the amout of chars stored in buf but it doesnt limit the amount of text echoed to the screen. :/
    Last edited by CtrlAltKick; 04-03-2002 at 04:13 PM.

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Hell if you're going for un-portable, just combine getch with
    >kbdhit and a counter. Much easier.
    Nonportable is pretty much the only way to do this. Seeing as how the requirement that he told me was that the input would look like this:
    Field: [<Input here> ]

    Which pretty much requires a flavor of gotoxy as well. Ah, the life of a programmer.

    >fgets( buf, bufLength, stdin );
    You should pay more attention to the thread , fgets is buffered input. The user can enter as much junk as they want, but only bufLength values will be assigned. fgets protects against buffer overflow, but not the buffer that is echoed to the screen.

    -Prelude
    My best code is written with the delete key.

  11. #11
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You should pay more attention to the thread , fgets is buffered input. The user can enter as much junk as they want, but only bufLength values will be assigned. fgets protects against buffer overflow, but not the buffer that is echoed to the screen.
    Yup. That's why I suggested kbdhit. Actually...

    You should use Pascal. It has much better screen handling functions by default

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 10:13 AM
  2. Need help from the gurus. homework
    By 1BadRbt in forum C Programming
    Replies: 11
    Last Post: 11-21-2006, 09:54 AM
  3. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  4. Perfect number...
    By Argo_Jeude in forum C++ Programming
    Replies: 8
    Last Post: 07-12-2005, 01:53 PM
  5. Limiting Characters in Edit Box :: MFC
    By kuphryn in forum Windows Programming
    Replies: 5
    Last Post: 06-02-2002, 10:21 AM