代码优化!
菜鸟写的一个密码登录系统的代码,以下可以优化吗?
[code=C/C++][/code]
#include<iostream>
#include<string>
using namespace std;
string password1="administrator";
string password2="user";
int xgpassword()
{
string xgpassword_1;
string xgpassword_2;
string xgpassword_3;
string xgpassword_4;
int xgmm;
cout<<"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"<<endl;
cout<<"$------------------修改密码-------------------$"<<endl;
cout<<"$-----1、administrator----------2、user-------$"<<endl;
cout<<"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"<<endl;
cout<<"请选择用户名:"<<endl;
cin>>xgmm;
switch(xgmm)
{
case 1:cout<<"请输入原始密码!"<<endl;
while(cin>>xgpassword_1)
if (xgpassword_1==password1)
{
cout<<"输入正确,请输入新密码!"<<endl;
cin>>password1;
cout<<"请重新确认新密码!"<<endl;
cin>>xgpassword_3;
if (xgpassword_3==password1)
{
cout<<"修改密码成功!"<<endl;
break;
}
else
{
cout<<"两次输入的密码不一致,请重新输入!"<<endl;
}
}
else
{
cout<<"输入错误,请重新输入!"<<endl;
}
case 2:cout<<"请输入原始密码!"<<endl;
while(cin>>xgpassword_2)
if (xgpassword_2==password2)
{
cout<<"输入正确,请输入新密码!"<<endl;
cin>>password2;
cout<<"请重新确认新密码!"<<endl;
cin>>xgpassword_3;
if (xgpassword_3==password2)
{
cout<<"修改密码成功!"<<endl;
break;
}
else
{
cout<<"两次输入的密码不一致,请重新输入!"<<endl;
}
}
else
{
cout<<"输入错误,请重新输入!"<<endl;
}
}
return 0;
}
int main()
{
string password_1;
string password_2;
int yh;
cout<<"-------------------------"<<endl;
cout<<"--------------------------------------------------"<<endl;
cout<<"***************PASSWOED SYSTEM********************"<<endl;
cout<<"---1、administrator 2、user 3、change password---"<<endl;
cout<<"--------------------------------------------------"<<endl;
cout<<"请选择用户名:"<<endl;
while(cin>>yh)
switch(yh)
{
case 1:cout<<"您选择的是administrator用户,请输入密码!"<<endl;
while(cin>>password_1)
if (password_1==password1)
{
cout<<"输入正确!"<<endl;
break;
}
else
{
cout<<"输入错误,请重新输入密码!"<<endl;
}
break;
case 2:cout<<"您选择是user用户,请输入密码!"<<endl;
while(cin>>password_2)
if(password_2==password2)
{
cout<<"输入正确!"<<endl;
break;
}
else
{
cout<<"输入错误,请重新输入密码!"<<endl;
}
break;
case 3:cout<<"修改密码!"<<endl;
xgpassword();
break;
}
return 0;
}
[解决办法]
好多代码重复的啊,像修改密码可以定义个函数的.还有整个程序基本都是对两个密码的操作,也可以写成函数的,自己再好好思考,让代码更简练,清晰.
------解决方案--------------------
仅供参考
- C/C++ code
#include <conio.h>#include <stdio.h>char pw[40];int i,ch;FILE *f;void main() { cprintf("\r\nPassword:"); i=0;pw[i]=0; while (1) { ch=getch(); if (ch==13 || i>=39) break; switch (ch) { case 27: cprintf("\rPassword: %40s"," "); cprintf("\rPassword: "); i=0;pw[i]=0; break; case 8: if (i>0) { i--; pw[i]=0; cprintf("\b \b"); } break; default: pw[i]=ch; i++; pw[i]=0; cprintf("*"); break; } } cprintf("\r\n"); f=fopen("password.txt","w"); fprintf(f,"%s\n",pw); fclose(f);}