自制 C++ 密码程序
说明: 代码发布之前,此程序出现了许多错误和bug(点击查看)
感谢@一位13岁的编程爱好者的帮助
注意: 作者使用的是 linux 系统,windows和macos 用户直接编译可能会报错
某些地方是为 linux 准备的,如果你用windows系统,需根据注释修改
话不多说,上代码:
//作者使用的是 linux 系统,windows和macos 用户直接编译可能会报错
#include <termios.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
// 以上头文件为 linux 获取字符的 getch() 准备
//如果你是 windows 系统,那么改成:
// #include<conio.h>
//由于作者不熟悉 macos 系统,所以没有关于 macos 的注释,macos 用户需自行琢磨
#include <iostream> // C++必备头文件
using namespace std; // 命名空间std
char getch() // linux 获取字符的 getch() ,windows 系统要直接删除这个函数
{
//以下不是核心,我就少注释了
char c = 0;
struct termios org_opts, new_opts;
int res = 0;
//----- store old settings -----------
res = tcgetattr(STDIN_FILENO, &org_opts);
assert(res == 0);
//---- set new terminal parms --------
memcpy(&new_opts, &org_opts, sizeof(new_opts));
new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
c = getchar();
//------ restore old settings ---------
res = tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
assert(res == 0);
return c;
}
std::string get() //获取密码
{
std::cout << "请输入密码:"; //提示文字,可修改或删掉
std::string PassWord; // 定义密码为字符串
while (1) // 循环
{
char a = getch(); // windows系统可能要改为_getch()
switch (a) //判断输入
{
case 10: // 获取回车(linux中编码为10),windows 系统可能是\r或\n
if (PassWord.size()) //密码长度大于0
std::cout << "\r\n"; //输出"换行",windows 系统可能只需要\n或\r
return PassWord; //返回密码并退出循环
break; //退出判断
case 127: // 获取退格(linux中编码为127),windows 系统可能是\b
if (PassWord.size())
{
std::cout << "\b \b"; // 向左移动光标并删除屏幕上的一个密码符号(替换成空格),不可修改但可删掉(同时删掉 std::cout << "*";)
PassWord.pop_back(); // 删除密码前一个字符
}
break;
default: //获取其他字符
PassWord += a; // 插入密码
std::cout << "*"; //显示密码符号,可修改或删掉(同时删掉 std::cout << "\b \b";)
break;
}
}
}
int main() //主函数
{
std::cout << get() << endl; //打印密码
return 0; // 正常时返回值为0
}
运行结果:
输入abcd,再按退格,再输入e
# g++ -o test a.cpp
# ./test
请输入密码:****abce