Reputation: 27
I didn't understand this function. Can someone explain the full code to me ? What does this line for *(pass+i) = temp_passP[i];
?
And also what does this mean printf \a printf \b
?
void get_password(char* pass)
{
char temp_passP[25];
int i=0;
while(1)
{
temp_passP[i]=getch();
if(temp_passP[i]==13){break;}
else if(temp_passP[i]==8)
{
if(i!=0) {
printf("\b \b");
i--;
} else {printf("\a");}
}
else
{
printf("*");
*(pass+i) = temp_passP[i];
i++;
}
*(pass+i)='\0'; what it means ?
}
}
Upvotes: 0
Views: 113
Reputation: 121
The first thing to understand about this function is that it's not very good. char temp_passP[25]
should just be int ch
, then all the references to char temp_passP[i]
can be ch
. With that change, it might be easier to see that the code is just reading characters from stdin via getch(), one character at a time, and inspecting each one.
First, it compares the character to 13, which is the ASCII code for Carriage Return. On some systems, when the user types ENTER, the system puts the two characters Carriage Return and Line Feed into the stdin stream. So this check is looking for the end line. (In other environments, ENTER generates just Line Feed (ASCII 10), so this code won't work there.)
The function then compares the character to 8, which is the ASCII code for Backspace. The code is checking to see if the user is deleting the last character entered. If so, it backs up the pointer into the pass
buffer and also prints that "\b \b"
sequence which erases the star for that character from the screen. If there are no characters in the pass
buffer, either because none have been entered yet or all have been deleted with Backspace, the "\a"
is intended to make the bell to ring.
If the character is nothing special, it is written into the pass
buffer with *(pass+i) = temp_passP[i];
(or *(pass+i) = ch;
).
*(pass+i) = '\0';
command makes sure the pass
buffer is always null terminated after the last character that hasn't been deleted.
Upvotes: 1
Reputation: 341
*(pass+i)
is equivalent to pass[i]
. You have to learn about pointers. '\b'
means backspace, it moves the cursor to left. '\a'
means alert, it makes beep or bell.
8 is equal to '\b'
. temp_passP[i]==8
means 'When the user pressed backspace key'. It moves the cursor to left, prints space, and since the cursor moved to right, it moves the cursor to left once more.
When the user pressed other keys, It prints '*'
and copies the input into pass[i]
.
In a nutshell, this program gets input until the user presses enter key and copies it into pass
.
Upvotes: 3