繁体   English   中英

C#中的char和int之间的区别

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM