2017-10-13 135 views
-3
static string ReadPassword(int length, char c) 

該方法應該允許您輸入字符串作爲密碼。 長度是密碼的最小長度和c是屏幕上顯示的每個數字密碼的字符。將字符串轉換爲密碼

有至少8個字符,在主輸入密碼使用:他/她的密碼

string pwd = ReadPassword(8, '●') 

用戶鍵入的字母。但是,在屏幕上,不會出現字母,而是存儲在c中的字符,例如項目符號「●」。

我該如何構建程序,以便爲控制檯eaven中鍵入的每個字符寫* *儘管我的方法以返回s結束?

+4

好的..但..你忘了問一個問題! –

+0

https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems –

+0

對不起,這是我的assigment,我真的不知道從哪裏開始。 –

回答

1

您可以設置光標位置輸入位置或使用ReadKey(true)試試這個:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.Write("Set password: "); 
     var password = ReadPassword(8, 'o'); 
     Console.WriteLine(); 
     Console.WriteLine($"Your password is: {password}"); 
     Console.ReadKey(); 
    } 

    static string ReadPassword(int length, char c) 
    { 
     var left = Console.CursorLeft; 
     var top = Console.CursorTop; 
     var password = new StringBuilder(); 
     for (int i = 0; i < length; i++) 
     { 
      password.Append(Console.ReadKey().KeyChar); 
      Console.SetCursorPosition(left + i, top); 
      Console.Write(c); 
     } 
     return password.ToString(); 
    } 
} 

你可以在這裏找到的文檔:https://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx

+0

這工作謝謝,我一直在嘗試2幾小時,並沒有設法找到我需要的版本。感謝幫助! –

2

在這裏你去。

class Program { 
     static void Main(string[] args) { 
      char ch;int len; 
      Console.WriteLine("Enter the Length of the Password: "); 
      len = Convert.ToInt32(Console.ReadLine()); 
      Console.WriteLine("Enter the Character for Password:"); 
      ch = Convert.ToChar(Console.Read()); 
      printPassword(len, ch); 
      Console.Read(); 
     } 
     public static void printPassword(int len,char ch) { 
      char ch1;String pass=""; 
      int i; 
      for (i = 0; i < len; i++) { 
       pass += Console.ReadKey(true); 
       Console.Write(ch); 
      } 
     } 
    } 
+0

謝謝,請問你是如何得出這個答案的,因爲它更重要的是 或我作爲學生能夠自己弄清楚這一點。你會在c#上重新閱讀任何書嗎? –

+0

馬丁的'Clean Code'和Gary McLean Hall的'Adaptive Code'對於初學者來說都是非常不錯的書。 – cSteusloff

+0

@cSteusloff非常感謝你的男人,這真的很好。 –