Home > Software engineering >  end a C program loop when Enter key is pressed
end a C program loop when Enter key is pressed

Time:09-03

I'm working on an input validation program in C. I have a function called show_password which accepts users input ranging from 8- 13 characters. The code is now only allowing user to enter until 13 characters so as to quit. I need to quit the program whenever a user presses enter for characters between 8-13 characters.

I have defined a macro:

#define PASSWORD_LENGTH 13

Here is my code

// password
void _password()
{

    char pass_word[PASSWORD_LENGTH];

    printf("\nEnter 8-13 character Password\n");
    for (j=0; j<=PASSWORD_LENGTH; j  )           //at this code is where i need to make the change
    {
        pass_word[j] = getch();     // Hidden password
        printf("*");
    }
    pass_word[j] = '\0';
    printf("\n");
    printf("password entered is:");
        for (j=0; pass_word[j] != '\0'; j   )
    {
        printf("%c",pass_word[j]);

    }
    getch();

}

CodePudding user response:

You can:

  • check if the character read from input is equal to '\n' or '\r' to detect when the user enters RETURN;
  • check if the index is greater or equal 8 (which means the user is pressing enter as 9th character or after);
  • use break keyword to quit the loop.

Example:

pass_word[j] = getch();
if ((pass_word[j] == '\n' || pass_word[j] == '\r') && j >= 8)
    break;

CodePudding user response:

getch() returns the ASCII value of the key pressed by the user as an input, enter key is a carriage return .When you press enter key, the ASCII value of Enter key is not returned, instead carriage return (CR) is returned.

\r is used as a carriage return character representing the return or enter key on keyboard similar stack overflow question

This code worked

// password
void _password()
{

    char pass_word[PASSWORD_LENGTH];

    printf("\nEnter 8-13 character Password\n");
   for (j=0; j<=PASSWORD_LENGTH; j  )
    {

        pass_word[j] = getch();
        printf("*");
        if (pass_word[j] == '\n' || pass_word[j] == '\r')
        break;
        
          // Hidden password

    }

    pass_word[j] = '\0';
    printf("\n");
    printf("password entered is:");
        for (j=0; pass_word[j] != '\0'; j   )
    {
        printf("%c",pass_word[j]);

    }
    getch();

}
  •  Tags:  
  • c
  • Related