Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print * in place of characters for reading passwords in C
In C programming, when handling passwords, it's important to hide the actual characters from being displayed on screen for security reasons. This involves replacing each character of the password with an asterisk (*) symbol.
Let's take an example to understand the problem −
Input: password Output: ********
Syntax
for(int i = 0; i < strlen(password); i++){
printf("*");
}
Example 1: Using Predefined Password String
The below program demonstrates how to replace each character of a password string with asterisks ?
#include <stdio.h>
#include <string.h>
int main() {
char password[50] = "password";
int length = strlen(password);
printf("Original password: %s<br>", password);
printf("Hidden password: ");
for(int i = 0; i < length; i++){
printf("*");
}
printf("<br>");
return 0;
}
Original password: password Hidden password: ********
Example 2: Reading Password from User Input
This example shows how to read a password from user input and display it as asterisks ?
#include <stdio.h>
#include <string.h>
int main() {
char password[50];
printf("Enter password: ");
fgets(password, sizeof(password), stdin);
/* Remove newline character if present */
password[strcspn(password, "<br>")] = '\0';
int length = strlen(password);
printf("Password entered: ");
for(int i = 0; i < length; i++){
printf("*");
}
printf("<br>");
return 0;
}
Enter password: mypassword Password entered: **********
Key Points
- The
strlen()function calculates the length of the password string. - A simple
forloop iterates through each character position. - Each character is replaced with an asterisk (*) during output.
- The original password string remains unchanged in memory.
Conclusion
Masking password characters with asterisks is a fundamental security practice in C programming. This approach ensures that sensitive information remains hidden from view while still allowing the program to process the actual password data.
Advertisements
