2012-10-17 57 views
-1

可能重複:
Hide password input on terminal如何顯示*爲每個輸入字符在C密碼 - 使字符無形

我要實現這一點:

$Insert Pass: 
User types: a (a immediately disappears & '*' takes its position on the shell) 
On the Shell : a 
Intermediate O/P: * 

User types: b (b immediately disappears & '*' takes its position on the shell) 
On the Shell : *b 
Intermediate O/P: ** 

User types: c (c immediately disappears & '*' takes its position on the shell) 
On the Shell : **c 
Final O/P  : *** 

我試過以下方法:

#include <stdio.h> 
#include <string.h> 

#define SIZE 20 

int main() 
{ 

    char array[SIZE]; 
    int counter = 0; 

    memset(array,'0',SIZE); 

    while ((array[counter]!='\n')&&(counter<=SIZE-2)) 
    { 
     array[counter++] = getchar(); 
     printf("\b\b"); 
     printf ("*"); 
    } 

    printf("\nPassword: %s\n", array); 

    return 0; 
} 

但我無法達到預期的輸出。此代碼無法使用戶鍵入的字符不可見&立即顯示'*'。

有人可以請指導我這一點。

謝謝。

最好的問候, 桑迪普·辛格

+2

我認爲這已經在這裏得到解決 - http://stackoverflow.com/questions/6856635/hide-password-input-on-terminal –

+0

@RudolfsBundulis是的,他們確實討論這一點。要走的路將是這樣的答案:http://stackoverflow.com/a/6869218/694576 – alk

回答

1

你的方法是行不通的;即使您可以覆蓋該字符,我也可以使用script(1)等工具運行您的命令並查看輸出。

正確的解決方案是將終端從烹飪切換到原始模式並關閉回聲。

第一次更改會讓您的程序看到每個輸入的字符(否則,shell將收集一行輸入並將其發送到您的進程,用戶按回車後)。

第二個更改阻止外殼/終端打印用戶輸入的內容。

See this article該怎麼做。

0

問題是getchar()等到用戶按下回車鍵,然後一次返回整個字符串。你想要的是一種在輸入一個字符後立即返回的方法。雖然沒有可移植的方式來做到這一點,但對於Windows,您可以在您的應用程序中使用#include <conio.h>,並用array[counter++] = _getch()替換array[counter++] = getchar(),它應該可以工作。

相關問題