2011-12-30 124 views
1

我試圖讀取一個密碼,而我讀它時,顯示* *。C++密碼字段

cout << "\n Insert password : "; 
loop1: 
    string passw1 = ""; 
    char ch = _getch(); 
    while (ch != 13) // enter = char 13 
    { 
     if (!isalnum(ch)) 
     { 
      cout << "\n\n Invalid character! Please insert the password again! "; 
      goto loop1; 
     } 

     passw1.push_back(ch); 
     cout << "*"; 
     ch = _getch(); 
    } 

如果我按例如,BACKSPACE或空格或非alpha數值的東西,一切都按計劃進行。問題是當我按下任何F鍵或DELETE,HOME,INSERT,END,PG UP,PG DOWN時,程序崩潰。你能幫我避免碰撞嗎?如果按下無效鍵,我想顯示一條錯誤消息,而不是讓我的程序崩潰。

+0

的問題是,'Del','Home'等不產生在首位字符 - 它們是移動的控制命令光標,就像箭頭鍵一樣。但是,您逐字讀取輸入字符,因此您無法使用它們來編輯當前正在寫入的行。這就是爲什麼他們不適合你的程序。 – 2011-12-30 17:33:22

+0

重新思考這個循環,'goto'在這裏既不需要也不是一個好主意 - 你在循環對象初始化 - 不知道這是否合法。 – Mat 2011-12-30 17:35:27

+0

您能否提供有關您的環境的其他信息?我使用MSVC 10在Windows 7上運行此代碼,但未看到任何崩潰。 – DRH 2011-12-30 17:36:10

回答

0

使用是字母數字功能 - isalnum(char c)以檢查參數c是十進制數字 或一個大寫或小寫字母。

然後濾除字符小於32或大於122是這樣的:if (c > 32 && c <122) { Get_Password(); }

這MS Windows特定下面的代碼是不可移植的。對於Linux/* NIX/BSD看到這一點:Hide password input on terminal

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

int main() 
{ 
    std::string password; 
    char ch; 
    const char ENTER = 13; 

    std::cout << "enter the password: "; 

    while((ch = _getch()) != ENTER) 
    { 

     if (ch > 32 && ch<122) 
     { 
      if (isalnum(ch)) 
      { 
       password += ch; 
       std::cout << '*'; 

      } 

     } 
    } 
    std::cout <<"\nYour password is : " << password<<"\n\n"; 
    return 0; 
} 
1

讓我們來看看,如果我理解你正在試圖做(在僞代碼)是什麼:

Prompt the user for a password 
Wait for the user to press any key 

While the key pressed is not the enter key 
    If the entered key is an alphanumeric 
     Add the character to the password string 
     Print an asterisk on the screen 
     Accept another character 
    Else 
     Alert the user that they entered a non-alphanumeric 
     Clear out the string and have the user start over again 
    End If 
End While 

如果不是你以後,再修改的味道。

我認爲正在發生的事情是,當您測試按下的按鍵時,您沒有捕獲所有可能的字符。如果DEL給你帶來麻煩,那麼找出如何捕捉它或處理它(從屏幕上刪除一個星號,並從字符串中刪除一個字符)。

祝你好運!

+0

是的,你明白我想要做什麼。那麼,我不知道如何處理'DEL'鍵..我知道它的ASCII代碼是127,但是,由於'isalnum()'函數,程序崩潰... – Teo 2011-12-30 18:04:48

+0

也許檢出'cin'看看它是否更有能力? – John 2011-12-30 18:12:48

1

它崩潰我的Win7 64位VS2010系統上也是如此。原來_gech()正在返回224刪除密鑰,這是-32簽名字符。這導致內部斷言isalnum()

我改變了charint(這是什麼_getch()正在恢復和isalnum()需要一個參數)和溢出問題就走了。 unsigned char也適用。

int main() 
{ 
    cout << "\n Insert password : "; 
loop1: 
    string passw1 = ""; 
    int ch = _getch(); 
    while (ch != 13) // enter = char 13 
    { 
     if (!isalnum(ch)) 
     { 
      cout << "\n\n Invalid character! Please insert the password again! "; 
      goto loop1; 
     } 

     passw1.push_back(ch); 
     cout << "*"; 
     ch = _getch(); 
    } 
    return 0; 
} 

產量(按壓DEL每次):

Insert password : 

Invalid character! Please insert the password again! * 

Invalid character! Please insert the password again! * 
+0

注意修復破壞的程序邏輯作爲OP的練習留下:) – JoeFish 2011-12-30 18:35:51