昨天在逛百度空间时,看到心烦意乱空间的一个c++例子,简单实现从控制台读入密码。无聊就改善之,使之满足
(1)输入密码时,以"*"回显。
(2)支持backspace。
比较简单...。
- #include <iostream>
- #include <conio.h>//_getch()
- #include <string>
- #include <cctype>
- using namespace std;
- class CKeyString
- {
- private:
- string m_strkey;
- public:
- void SetKey();
- bool Range();
- friend istream& operator >> (istream& is,CKeyString * str);
- string ToString() const ;
- };
- bool CKeyString::Range()
- {
- string::size_type n = m_strkey.size();
- return (n < 11 && n > 5);
- }
- void CKeyString::SetKey()
- {
- int n = 0;
- string tempkey;
- while(1)
- {
- if(n)
- cout<<"Input the key again :"<<endl;
- else
- cout<<"Input the key (6b~10b): "<<endl;
- cin>>this;
- n++;
- cout<<endl;
- if(n == 1)
- {
- if(m_strkey.empty())
- {
- n = 0;
- cout<<"can't be empty! input again..."<<endl;
- }
- else
- if(!Range())
- {
- cout<<"the key isn't content..again"<<endl;
- n = 0;
- }
- else
- tempkey = m_strkey;
- m_strkey = "";
- }
- else//n == 2
- {
- if(m_strkey == tempkey)
- {
- cout<<"input succeedly..."<<endl;
- break;
- }
- cout<<"not the same...again"<<endl;
- n = 0;
- m_strkey = "";
- tempkey = "";
- }
- }
- }
- string CKeyString::ToString() const
- {
- return m_strkey;
- }
- istream& operator >> (istream& is,CKeyString *str)
- {
- char ch = '/n';
- int size = 0;
- while((ch = _getch()) != 13)
- {
- if(isalnum(ch))
- {//key只可为数字和字母
- str->m_strkey.push_back(ch);
- cout<<"*";
- size++;
- }
- else
- if(ch == '/b')//ch == 8
- {//退格键
- if(str->m_strkey.empty()== false)
- {
- str->m_strkey.erase(str->m_strkey.erase(str->m_strkey.end()-1));
- cout<<'/b'<<' '<<'/b';
- size--;
- }
- }
- }
- return is;
- }
- //测试
- int main()
- {
- CKeyString ks;
- ks.SetKey();
- cout<<"the key is: "<<endl;
- cout<<ks.ToString()<<endl;
- return 0;
- }
其中退格实现cout<<'/b'<<' '<<'/b',有点投机取巧。不过不知道如何对控制台的缓冲进行操作,就这样了。
期待有更好的实现方式....