C/C++: 控制台输入密码, 用*号掩藏

//此代码有一个网友所写

#include 
<iostream>
#include 
<conio.h>

/**
 * 秘密在于conio.h中的getch()从键盘中读取字符时,并不会在屏幕上输出已经输入的字符,
 * 而用一个putch('*')来哄骗,代表已经输入一个字符
 * 怪不得这个头文件要叫conio.h, con的意思就有哄骗,看来就是由此而来.
 
*/


using namespace std;

int main() {
        
char* password;
        
char* passwordConfirm;

        
int length = 4;
        password 
= new char[length + 1];
        passwordConfirm 
= new char[length + 1];

        
char* p = NULL;
        
int count = 0;

        cout 
<< "Input password : ";
        p 
= password;
        count 
= 0;
        
//fflush(stdin);
        while (((*= getch()) != 13&& count < length) {
                
// 这里不是'\n'(10), new line
                
// 而是'\r'(13), reback. 即是按下回车键,好像这个东西是linux的.
                
// 主要是与getch这个函数有关.
                putch('*');
                fflush(stdin);

                p
++;
                count
++;
        }

        password[count] 
= '\0';

        cout 
<< endl << "Confirm the password : ";
        p 
= passwordConfirm;
        count 
= 0;
        
//fflush(stdin);
        while (((*= getch()) != 13&& count < length) {
                putch(
'*');
                fflush(stdin);

                p
++;
                count
++;
        }

        passwordConfirm[count] 
= '\0';

        cout 
<< endl;
        
if (strcmp(password, passwordConfirm) == 0{
                cout 
<< "The password is right." << endl;
                cout 
<< password << endl;
        }
 else {
                cout 
<< "Confirm password fail." << endl;
                cout 
<< password << endl << passwordConfirm << endl;
        }


        
return 0;
}


posted on 2009-05-12 10:44 弹杯一笑 阅读(776) 评论(0)  编辑 收藏 引用 所属分类: c++笔记


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2009年5月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿(2)

随笔分类(7)

随笔档案(4)

搜索

最新评论

阅读排行榜

评论排行榜