关于c# read( )使用注意缓冲区赘余输入(附代码)

Console.ReadLine() 从控制台读取用户输入一行, 得到是 String 类型

Console.Read() 一次只读入一个字符的ASSIC码, 得到是 Int 类型

read()方法在键入enter时终止,并且会在输入内容后面追加行终止序列

read()时从缓冲区 读入单个字符的int 类型  在使用read()时 注意如果使用回车(enter)结束时,就会把换行和回车符一同放入缓冲区!!!

所以会把换行回车符一同读入。

这样就会造成数据出错

调试代码为:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace test1
{
    class Program
    {
        static void Main(string[] args)
        {
            Boolean flag = true;
           string s;
            // char s;
            string mail, psw;
            while (flag)
            {
                Console.WriteLine("您是否同意本服务条款?  Y/N");
             //  s = (char)Console.Read();    // 缓冲区 里存入啦 字符 回车 换行 三个字符 会挨个读入 所以会三次错误
              s = Console.ReadLine();

               //if (s == 'y' || s == 'y')
              if (s == "Y" || s == "y")
                {
                    flag = false;
                    Console.WriteLine("您已同意本服务条款!!");
                    Console.WriteLine("请输入邮箱地址进行注册");
                    mail = Console.ReadLine();
                    while (string.IsNullOrEmpty(mail))
                    {
                        Console.WriteLine("输入邮箱地址为空,请重新输入");
                        mail = Console.ReadLine();
                    }
                    Console.WriteLine(" 请输入密码");
                    psw = Console.ReadLine();
                    while (string.IsNullOrEmpty(psw))
                    {
                        Console.WriteLine("输入密码为空,请重新输入");
                        psw = Console.ReadLine();
                    }
                    Console.WriteLine("注册成功");
                    Console.WriteLine("注册邮箱为:" + mail + "@126.com");
                    Console.WriteLine("密码为:" + psw);

                }
                else
                {
                    Console.WriteLine("请输入正确指令");
                }
            }

        }
    }
}

可以把上面的注释换成read ( ) 可以试试 就会 循环三次 第一次是你输入的字符,然后是换行符,最后是回车符。



 

posted @ 2016-09-15 10:17  Joe.Smith  阅读(763)  评论(0编辑  收藏  举报