首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C#小程序 有关问题

2012-02-17 
C#小程序 问题static void Main(string[] args){char cint l 0, d 0, o 0Console.WriteLine(请输

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();        } 

热点排行