日期:2014-05-18  浏览次数:20987 次

C#小程序 问题
static void Main(string[] args)
  {
  char c;
  int l = 0, d = 0, o = 0;
  Console.WriteLine("请输入字符:");
  c = (char)Console.Read();
  while (c!= '\n')
  {
  if (c>= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
  l++;
  else if (c >= '0' && c <= '9')
  d++;
  else
  o++;
  c = (char)Console.Read();

  }
  Console.WriteLine("{0},{1},{2}",l,d,o);
  Console.ReadLine();
  }

 问题:
  每次输入非数字或非字母的个数总是多一个? 这是为什么?用C语言写之后就没有这种情况 。。


------解决方案--------------------
C# code

            int l = 0, d = 0, o = 0;
            Console.WriteLine("请输入字符:");
            string str = Console.ReadLine();
            foreach (char c in str)
            {
                if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
                    l++;
                else if (c >= '0' && c <= '9')
                    d++;
                else
                    o++;
            }
            Console.WriteLine("{0},{1},{2}", l.ToString(), d.ToString(), o.ToString());

             Console.ReadKey();

------解决方案--------------------
因为回车符是'\r\n'吗,而循环没判断'\r'。看第5行。

C# code

        static void Main(string[] args)
        {
            char c;
            int l = 0, d = 0, o = 0;
            Console.WriteLine("请输入字符:");
            c = (char)Console.Read();
            while (c != '\n' && c != '\r')
            {
                if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
                    l++;
                else if (c >= '0' && c <= '9')
                    d++;
                else
                    o++;
                c = (char)Console.Read();

            }
            Console.WriteLine("{0},{1},{2}", l, d, o);
            Console.ReadLine();
        }