c语言输入密码并将密码掩盖住

153 阅读1分钟

​本文已参与「新人创作礼」活动,一起开启掘金创作之路。

#include <stdio.h>
#include<windows.h>
#include<stdlib.h>

//获取光标的位置x
int wherex()
{
    CONSOLE_SCREEN_BUFFER_INFO pBuffer;
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pBuffer);
    return (pBuffer.dwCursorPosition.X+1);
}
//获取光标的位置y
int wherey()
{
    CONSOLE_SCREEN_BUFFER_INFO pBuffer;
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pBuffer);
    return (pBuffer.dwCursorPosition.Y+1);
}
//设置光标的位置
void gotoxy(int x,int y) 
{
    COORD c;
    c.X=x-1;
    c.Y=y-1;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);
} 

void main()
{
    int i,j;
	int x,y;
	char ch[20];
    printf("密码:");
	i = -1;
	do
	{		
		i++;
		ch[i]=getch();  //输入密码。
		while(ch[i]==8&&i>=0) //删除键时将前面的*号用空白掩盖。
		{
		   i--;
		   if(i>=0)
		   {
		   x=wherex();
	       y=wherey();
		   gotoxy(x-1,y);
		   printf(" ");
		   x=wherex();
	       y=wherey();
		   gotoxy(x-1,y);
		   }
		   ch[i]=getch();	  
		}
		if(i>=0&&ch[i]!=13&&ch[i]!=8)
		{
		x=wherex();
	    y=wherey();
		gotoxy(x,y);
		printf("*");   //将输入的密码位置用*号掩盖。
		
		}
		
	}while(ch[i]!=13);  //当输入回车键时退出输入。
	ch[i]='\0';
	printf("\n\n\n%s\n\n",ch);	
}

上面的代码运行如下图: