Reputation: 29
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();
}
Upvotes: 0
Views: 118
Reputation: 2281
You can:
'\n'
or '\r'
to detect when the user enters RETURN
;break
keyword to quit the loop.Example:
pass_word[j] = getch();
if ((pass_word[j] == '\n' || pass_word[j] == '\r') && j >= 8)
break;
Upvotes: 2
Reputation: 29
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();
}
Upvotes: 0