日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

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

發(fā)布時(shí)間:2024/2/28 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C# Console.ReadLine()方法的使用 以及利用其返回值null终止输入 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

官方解釋

ReadLine方法以同步方式執(zhí)行。 即,被阻止,直至讀取行或按下 Ctrl + Z 鍵盤組合。 In屬性返回TextReader對(duì)象,它表示標(biāo)準(zhǔn)輸入的流并具有這兩個(gè)同步 TextReader.ReadLine方法和異步TextReader.ReadLineAsync方法。 但是,當(dāng)用作控制臺(tái)的標(biāo)準(zhǔn)輸入流, TextReader.ReadLineAsync同步而不是以異步方式執(zhí)行,并返回Task僅完成讀取的操作后。

如果此方法將引發(fā) OutOfMemoryException異常,而在基礎(chǔ)讀取器的位置 Stream對(duì)象高級(jí)的字符的方法是可以讀取,但已讀入內(nèi)部的字符數(shù)ReadLine緩沖區(qū)將被丟棄。 由于不能更改流中讀取器的位置,因此已讀取的字符是不可恢復(fù),并可以訪問(wèn)僅通過(guò)重新初始化 TextReader。 如果流中的初始位置是未知或流不支持查找,基礎(chǔ) Stream還需要重新初始化。 若要避免這種情況并生成可靠的代碼,應(yīng)使用 KeyAvailable屬性和ReadKey只讀方法和應(yīng)用商店中預(yù)先分配的緩沖區(qū)的字符。

如果該方法是從控制臺(tái)讀取輸入時(shí)按 Ctrl + Z 字符,該方法返回 null。 這使用戶以防止進(jìn)一步的鍵盤輸入時(shí)ReadLine在循環(huán)中調(diào)用方法。 下面的示例闡釋了這種情況。

官方示例

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個(gè)值,以回車分隔。將逐行輸出int型的你剛輸入的數(shù)字

輸入示例

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();用標(biāo)點(diǎn)分開//string[] vals = value.Split(',');輸出并轉(zhuǎn)化為int數(shù)組//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}個(gè):{1}", i + 1, num[i]));//}int[] a = new int[1000];int i = 0;string str = "";int num = 0;//輸入Console.WriteLine("輸入10個(gè)值,以回車分隔");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]);}}} }

查看監(jiān)視
可看到變量的存儲(chǔ)方式

總結(jié)

以上是生活随笔為你收集整理的C# Console.ReadLine()方法的使用 以及利用其返回值null终止输入的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。