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]);}}} }查看監視
可看到變量的存儲方式
總結
以上是生活随笔為你收集整理的C# Console.ReadLine()方法的使用 以及利用其返回值null终止输入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 温度转换
- 下一篇: C# 窗体输入个人信息 存入txt 窗体