2010-12-21 26 views
2

最簡單的方法是什麼,我可以存儲用戶輸入的密碼,同時仍然保持密碼隱藏?存儲密碼,同時保持getch的完整性()

char password[9]; 
    int i; 
    printf("Enter your password: "); 
    for (i=0;i<9;i++) 
    { 
    password[i] = getch(); 
    printf("*"); 
    } 
    for (i=0;i<9;i++) 
    printf("%c",password[i]); 
    getch(); 
    } 

我想保存密碼,所以我可以做一個簡單的if (password[i] == root_password)所以正確的密碼,繼續上。

+0

你用用C'getch' ++,而不是'cin.get'有什麼特別的原因嗎? – 2010-12-21 06:51:23

+0

沒理由。找不到其他合適的方法。 – 2010-12-21 07:02:44

+2

@Cody:getch不會回顯輸入,不像典型的cin.get() – ybungalobill 2010-12-21 07:11:57

回答

0

你的問題似乎是你沒有檢查換行'\ n'和文件結束。

printf("Enter your password: "); 
char password[9]; 
int i; 
for (i = 0; i < sizeof password - 1; i++) 
{ 
    int c = getch(); 
    if (c == '\n' || c == EOF) 
     break; 
    } 
    password[i] = c; 
    printf("*"); 
} 
password[i] = '\0'; 

這樣一來,密碼最終會被一個ASCIIZ字符串,適用於puts打印,printf("%s", password),或者 - 關鍵...

if (strcmp(password, root_password)) == 0) 
    your_wish_is_my_command(); 

注意,我們讀到最多8個字符入因爲我們需要NUL終結符的一個額外字符。如果你願意,你可以增加。

+0

爲什麼說這個部分的所有變量都是未聲明的? – 2010-12-21 07:36:42

+0

Josh:如果你也使用它,你是否包含了printf()和getch(),strcmp()的必要頭文件?否則,我不能說沒有看到你的確切代碼 - 爲什麼不把它粘貼到你的問題上面,並列出確切的編譯器錯誤和行號......? – 2010-12-21 08:07:29

+0

你沒有正確使用sizeof。首先,你失蹤(),並且它返回一個以字節爲單位的大小。用sizeof代替整個hoopla,你可以放10個。-1阻礙你,因爲<是小於,不小於或等於操作符。 – 2010-12-21 08:55:51

0

您需要在Windows中使用控制檯API。以下是禁用控制檯窗口中的回顯的代碼片段。功能SetConsoleMode()用於控制回聲(除其他外)。我保存舊模式,以便一旦檢索到密碼,我就可以恢復控制檯。

而且,*ConsoleMode()函數需要控制檯輸入緩衝區的句柄。如何獲得這些緩衝區的句柄在CreateFile()的MSDN文檔中有描述。

int main(int argc, char* argv[]) 
{ 
    char password[100] = { 0 }; 
    printf("Enter your password: "); 

    HANDLE hConsole = ::CreateFile("CONIN$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); 

    DWORD dwOldMode; 
    ::GetConsoleMode(hConsole, &dwOldMode); 
    ::SetConsoleMode(hConsole, dwOldMode & ~ENABLE_ECHO_INPUT); 

    bool bFinished = false; 
    while(!bFinished) { 
     if(!fgets(password, sizeof(password)/sizeof(password[0]) - 1, stdin)) { 
      printf("\nEOF - exiting\n"); 
     } else 
      bFinished = true; 
    } 

    ::SetConsoleMode(hConsole, dwOldMode | ENABLE_ECHO_INPUT); 
    printf("\nPassword is: %s\n", password); 

    return 0; 
} 
0

由於我們是在C++和Windows做到這一點:

#include <iostream> 
#include <string> 
#include <conio.h> //_getch 
#include <Windows.h> //VK_RETURN = 0x0D 

using namespace std; 

string read_password() 
{ 
    string pass; 
    cout << "Enter your password: "; 

    int character = 0; 
    while(VK_RETURN != (character = _getch())) 
    { 
     cout << '*'; 
     pass += static_cast<char>(character); 
    } 

    cout << std::endl; 
    return pass; 
} 

int main() 
{ 
    string root_password = "anypass123"; 
    string pass = read_password(); 

    if (pass == root_password) 
    { 
     cout << "password accepted" << endl; 
    } 

    return 0; 
} 

編譯&測試