Home > Net >  how to limit digit amount when getting user input and how to automatically press enter
how to limit digit amount when getting user input and how to automatically press enter

Time:12-29

I want to write a line of code that when you enter 4 numbers the computer automatically presses enter after a set numbers of digit was entered, how do i do it?

CodePudding user response:

A more or less portable solution using GNU readline:

#include <readline/readline.h>
#include <stdio.h>
#include <stdlib.h>

static int limit_rl(FILE *f)
{
    if (rl_end >= 4)
    {
        return '\n';
    }
    return rl_getc(f);
}

int main(void)
{
    char *str;

    rl_getc_function = limit_rl;
    str = readline("> ");
    printf("%s\n", str);
    free(str);
    return 0;
}

CodePudding user response:

it depends on your OS:

as an example, on a linux system, with system calls:

#include <stdio.h>
#include <stdlib.h>

int main(void){
  int c;
  int passwd[4]={0};
  system ("/bin/stty raw"); //use system call to make terminal send all keystrokes directly to stdin
  for(unsigned short nb_char = 0;  nb_char < 4; nb_char  ) 
  {
    do
    {
        c=getchar();
    }while((c < 48) || (c > 57));
    passwd[nb_char] = c;
  }
  printf("\npassword is:");
  for(unsigned short nb_char = 0;  nb_char < 4; nb_char  ) 
  {
      putchar(passwd[nb_char]);
  }
  system ("/bin/stty cooked");//use system call to set terminal behaviour to more normal behaviour
  return 0;
}

output is:

1234
password is:1234

for windows, see getch():

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main(void){
  int c;
  int passwd[4]={0};

  for(unsigned short nb_char = 0;  nb_char < 4; nb_char  ) 
  {
    do
    {
        c=getch();
    }while((c < 48) || (c > 57));
    passwd[nb_char] = c;
  }
  printf("\npassword is:");
  for(unsigned short nb_char = 0;  nb_char < 4; nb_char  ) 
  {
      putchar(passwd[nb_char]);
  }
  return 0;
}

See this answer for a complete answer

  • Related