[英]Difference between the char and int in C#
創建一個C#程序以提示用戶從問題的答案選項列表中選擇正確的答案,如果答案是錯誤的,則嘗試使用do while循環再次提示相同的問題,但該方法無法正常工作。
class Program
{
static void Main(string[] args)
{
char UserChoice = ' ';
do
{
Console.WriteLine("What is the command keyword to exit a loop in C#?");
Console.WriteLine("a.quit");
Console.WriteLine("b.continue");
Console.WriteLine("c.break");
Console.WriteLine("d.exit");
UserChoice = ' ';
Console.WriteLine("Please enter a b c or d");
UserChoice = (char)Console.Read();
switch (UserChoice)
{
case 'a': Console.WriteLine("wrong ans"); break;
case 'b': Console.WriteLine("wrong ans"); break;
case 'd': Console.WriteLine("wrong ans"); break;
case 'c': Console.WriteLine("right"); break;
default: Console.WriteLine("Bad choice {0}", UserChoice); break;
}
} while (UserChoice == 'a' || UserChoice == 'b' || UserChoice == 'd');
}
}
但是,如果我在此程序中使用int而不是char並將a,b,c和d替換為1、2、3和4,則此程序可以正常工作。 使用char時,請有人可以解釋一下此代碼中的錯誤。
如果要讀取單個字符,則應使用Console.ReadKey
。
Console.Read
等待來自控制台的輸入,這意味着在大多數shell中讀取整行,然后將輸入的第一個字符的ASCII值作為int
。
如果您僅使用ReadKey
,則可以獲得代表下一個按下char
的實際char
,而不必擔心如何將所獲得的內容轉換為char
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.