#include #include #include #define N 20" />

小言_互联网的博客

C语言模拟简易密码的输入(不可视)

256人阅读  评论(0)

C语言模拟简易密码的输入(不可视)

利用getch函数提供用户输入,每输入一个字符,判断用户输入的字符,合理的字符将其保存为密码字符,然后在屏幕上输出一个"*"。

  1. 代码实现:
 //用getch函数实现不可视密码输入
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>

#define N 20

void in_password(char pw[]);
void print_password(char pw[]);

void in_password(char pw[])
{
	char ch, pw2[N];
	memset(pw2, '\0', N * sizeof(char));
	int i = 0;
	_Bool flag = 0;                               //判断是否是二次输入密码
	while (ch = _getch())
	{
		if (ch == '\r') 								
		{
			putchar('\n');
			if (*pw2 == '\0')
			{
				printf("请重新输入确认是否无误\n");
				i = 0;
				flag = 1;
				continue;
			}
			else if (strcmp(pw, pw2)!=0)
			{
				printf("两次输入的密码不一致,请重新输入\n");
				memset(pw2, '\0', N * sizeof(char));                  //输入错误后重置保存二次输入密码的数组
				i=0;
				continue;
			}
			else
			{
				break;
			}
			
		}
		else if (ch == ' ')                               //空格不能设置为密码字符
		{
			continue;
		}
		else if (ch == '\b')                        
		{
			if (!flag)
			{
				if (*pw == '\0')
				{
					continue;
				}
				else
				{
					printf("\b \b");                   //实现退格(删除输入)
					*(pw + i - 1) = '\0';
					i--;
				}
			}
			else
			{
				if (*pw2 == '\0')
				{
					continue;
				}
				else
				{
					printf("\b \b");                 //实现退格(删除输入)
					*(pw2 + i - 1) = '\0';
					i--;
				}
			}
			
		}
		else
		{
			if (!flag)
			{
				*(pw + i) = ch;           //将用户输入合理的字符存入数组
				printf("*");
				i++;
			}
			else
			{
				*(pw2 + i) = ch;           //将用户输入合理的字符存入数组
				printf("*");
				i++;
			}
			
		}
	}
}

void print_password(char pw[])
{
	if (*pw == '\0')
	{
		printf("还未输入任何密码\n");
	}
	else
	{
		printf("您输入的密码是:%s\n", pw);
	}
}
int main(void)
{
	char pw[N];
	memset(pw, '\0', N * sizeof(char));
	printf("请输入密码\n");
	in_password(pw);
	//print_password(pw);          //显示输入的密码,自行验证
	system("pause");
	return 0;
}

  • vscode中运行的结果:

转载:https://blog.csdn.net/KK1433223KK/article/details/102094745
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场