C# Console.ReadLine()方法的使用 以及利用其返回值null终止输入

官方解释

ReadLine方法以同步方式执行。 即,被阻止,直至读取行或按下 Ctrl + Z 键盘组合。 In属性返回TextReader对象,它表示标准输入的流并具有这两个同步 TextReader.ReadLine方法和异步TextReader.ReadLineAsync方法。 但是,当用作控制台的标准输入流, TextReader.ReadLineAsync同步而不是以异步方式执行,并返回Task仅完成读取的操作后。

如果此方法将引发 OutOfMemoryException异常,而在基础读取器的位置 Stream对象高级的字符的方法是可以读取,但已读入内部的字符数ReadLine缓冲区将被丢弃。 由于不能更改流中读取器的位置,因此已读取的字符是不可恢复,并可以访问仅通过重新初始化 TextReader。 如果流中的初始位置是未知或流不支持查找,基础 Stream还需要重新初始化。 若要避免这种情况并生成可靠的代码,应使用 KeyAvailable属性和ReadKey只读方法和应用商店中预先分配的缓冲区的字符。

如果该方法是从控制台读取输入时按 Ctrl + Z 字符,该方法返回 null。 这使用户以防止进一步的键盘输入时ReadLine在循环中调用方法。 下面的示例阐释了这种情况。

官方示例

using System;

public class Example
{
   public static void Main()
   {
      string line;
      Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
      Console.WriteLine();
      do { 
         Console.Write("   ");
         line = Console.ReadLine();
         if (line != null) 
            Console.WriteLine("      " + line);
      } while (line != null);   
   }
}
// The following displays possible output from this example:
//       Enter one or more lines of text (press CTRL+Z to exit):
//       
//          This is line #1.
//             This is line #1.
//          This is line #2
//             This is line #2
//          ^Z
//       
//       >

我的代码 C#

本程序用法:输入10个值,以回车分隔。将逐行输出int型的你刚输入的数字

输入示例

1
22
33
44
55
66
77
88
99
100

输出示例

1
22
33
44
55
66
77
88
99
100

代码

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

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            输入一行
            //string value = Console.ReadLine();

            用标点分开
            //string[] vals = value.Split(',');

            输出并转化为int数组
            //Console.WriteLine("分开展示各值");
            //int[] num = new int[vals.Length];
            //for (int i = 0; i < vals.Length; i++)
            //{
            //    num[i] = int.Parse(vals[i]);
            //    Console.WriteLine(string.Format("第{0}个:{1}", i + 1, num[i]));
            //}

            int[] a = new int[1000];
            int i = 0;
            string str = "";
            int num = 0;

            //输入
            Console.WriteLine("输入10个值,以回车分隔");
            while (str != null)
            {
                str = Console.ReadLine();
                num = int.Parse(str);
                a[i] = num;
                i++;

                if (i == 10) break;
            }

            //输出
            int j;
            for (j = 0; j < i; j++)
            {
                Console.WriteLine(a[j]);
            }
        }
    }
}

查看监视
可看到变量的存储方式
在这里插入图片描述

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值