记一个密码输入demo

#ifdef _WIN32
#include <conio.h>
#include <windows.h>
#else
#include <termios.h>
#endif
#include <iostream>
#include <ctype.h>
#include <string>
#include <errno.h>
#include <cstring>

#define PWD_MAX_LEN (64)
#define PWD_MIN_LEN (8)

bool IsSpeChar(char c)
{
	std::string spechars = "'-!\"#$%&()*,./:;?@[]^_`{|}~+<=>";
	size_t pos = spechars.find(c);

	if (std::string::npos != pos)
	{
		return true;
	}
	return false;
}

int GetChar(char& chr)
{
#ifdef _WIN32
	while(_kbhit() == 0)
	{
		Sleep(100);
	}
	chr = _getch();
#else
	struct termios org_opts, new_opts;
	int r = tcgetattr(STDIN_FILENO, &org_opts);
	if (-1 == r)
	{
		return -errno;
	}

	memcpy(&new_opts, &org_opts, sizeof(new_opts));
	new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL); 
	new_opts.c_cc[VMIN] = 1;
	r = tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
	if (-1 == r)
	{
		return -errno;
	}

	chr = getchar();
	r = tcsetattr(STDIN_FILENO, TCSANOW, &org_opts); 
	if (-1 == r)
	{
		return -errno;
	}
#endif
	return 0;
}

int Enter(std::string& pwd)
{
	int flags[4] = {0};		// upper, lower, digit, special

	while(true)
	{
		char c;
		int r = GetChar(c);
		if(r < 0)
		{
			return r;
		}

#ifdef _WIN32
		if (0 == c)
		{
			return -1;
		}
		if (13 == c)
		{
			break;
		}
#else
		if (c == '\n')
		{
			break;
		}
#endif

		if (pwd.size() > PWD_MAX_LEN)
		{
			return -1;
		}

		if (isupper(c))
		{
			flags[0] = 1;
		}
		else if (islower(c))
		{
			flags[1] = 1;
		}
		else if (isdigit(c))
		{
			flags[2] = 1;
		}
		else if (IsSpeChar(c))
		{
			flags[3] = 1;
		}
#ifdef _WIN32
		else if (8 == c)
#else
		else if (127 == c) // delete
#endif
		{
			if (!pwd.empty())
			{
				pwd.erase(pwd.end() - 1);
				putchar('\b');
				putchar(' ');
				putchar('\b');
			}
			continue;
		}
		else
		{
			return -1;
		}

		pwd += c;
		putchar('*');
	}

	if (pwd.size() < PWD_MIN_LEN)
	{
		return -1;
	}

	for (size_t i = 0; i < 4; ++i)
	{
		if (0 == flags[i])
		{
			return -1;
		}
	}
	return 0;
}

int main()
{
	std::string pwd;
	std::cout << "Enter password:";
	Enter(pwd);
	std::cout << "\n" << pwd << std::endl;
	return 0;
}

执行示例:

posted @ 2024-02-01 11:13  HOracle  阅读(26)  评论(0编辑  收藏  举报