可以的
授人以渔,不授人以鱼。
#include <Windows.h> #include <cstdio> #include <cstring> #include <cctype> #include <conio.h> HANDLE hOutput; const int K_BACKSPACE = 0x08; const int K_ENTER = 0x0D; void Pause(void); void ClearScreen(void); void GotoXY(short x, short y); void GotoXY(COORD pos); void main(void) { hOutput = GetStdHandle(STD_OUTPUT_HANDLE); if (hOutput == INVALID_HANDLE_VALUE) { return; } ClearScreen(); const size_t length = 8; char message[] = "请输入密码: "; COORD pos = { 5, 5 }; GotoXY(pos); printf_s("%s________", message); GotoXY(pos.X + strlen(message), pos.Y); int ch; size_t counter = 0; char password[length]; do { ch = _getch(); switch (ch) { case 0xE0: ch = _getch(); break; case K_BACKSPACE: --counter; CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(hOutput, &info); GotoXY(info.dwCursorPosition.X - 1, info.dwCursorPosition.Y); _putch('_'); GotoXY(info.dwCursorPosition.X - 1, info.dwCursorPosition.Y); break; default: if (isalnum(ch)) { password[counter++] = ch; _putch('*'); if (counter >= length) { ch = K_ENTER; } } break; } } while (ch != K_ENTER); password[counter] = '\0'; GotoXY(pos.X, pos.Y + 1); printf_s("您输入的密码是: %s", password); Pause(); } void Pause(void) { GotoXY(0, 24); printf_s("Press any key to continue..."); _getch(); } void ClearScreen(void) { CONSOLE_SCREEN_BUFFER_INFO info; DWORD number; COORD pos = { 0, 0 }; GetConsoleScreenBufferInfo(hOutput, &info); FillConsoleOutputCharacterA(hOutput, ' ', info.dwSize.X * info.dwSize.Y, pos, &number); GotoXY(pos); } void GotoXY(COORD pos) { SetConsoleCursorPosition(hOutput, pos); } void GotoXY(short x, short y) { COORD pos = { x, y }; SetConsoleCursorPosition(hOutput, pos); }