Console.ReadLine 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
从标准输入流中读取下一行字符。
public:
static System::String ^ ReadLine();
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static string? ReadLine();
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static string? ReadLine();
public static string ReadLine();
[<System.Runtime.Versioning.UnsupportedOSPlatform("android")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member ReadLine : unit -> string
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member ReadLine : unit -> string
static member ReadLine : unit -> string
Public Shared Function ReadLine () As String
返回
输入流中的下一行字符,或者 null 如果没有更多行可用。
- 属性
例外
出现 I/O 错误。
内存不足,无法为返回的字符串分配缓冲区。
下一行字符中的字符数大于 Int32.MaxValue。
示例
以下示例需要两个命令行参数:现有文本文件的名称以及要向其写入输出的文件的名称。 它将打开现有的文本文件,并将标准输入从键盘重定向到该文件。 它还会将标准输出从控制台重定向到输出文件。 然后,它使用 Console.ReadLine 该方法读取文件中的每一行,将四个空格的每个序列替换为制表符,并使用 Console.WriteLine 该方法将结果写入输出文件。
using System;
using System.IO;
public class InsertTabs
{
private const int tabSize = 4;
private const string usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
public static int Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine(usageText);
return 1;
}
try
{
// Attempt to open output file.
using (var writer = new StreamWriter(args[1]))
{
using (var reader = new StreamReader(args[0]))
{
// Redirect standard output from the console to the output file.
Console.SetOut(writer);
// Redirect standard input from the console to the input file.
Console.SetIn(reader);
string line;
while ((line = Console.ReadLine()) != null)
{
string newLine = line.Replace(("").PadRight(tabSize, ' '), "\t");
Console.WriteLine(newLine);
}
}
}
}
catch(IOException e)
{
TextWriter errorWriter = Console.Error;
errorWriter.WriteLine(e.Message);
errorWriter.WriteLine(usageText);
return 1;
}
// Recover the standard output stream so that a
// completion message can be displayed.
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
Console.WriteLine($"INSERTTABS has completed the processing of {args[0]}.");
return 0;
}
}
open System
open System.IO
let tabSize = 4
let usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt"
[<EntryPoint>]
let main args =
if args.Length < 2 then
Console.WriteLine usageText
1
else
try
// Attempt to open output file.
use reader = new StreamReader(args[0])
use writer = new StreamWriter(args[1])
// Redirect standard output from the console to the output file.
Console.SetOut writer
// Redirect standard input from the console to the input file.
Console.SetIn reader
let mutable line = Console.ReadLine()
while line <> null do
let newLine = line.Replace(("").PadRight(tabSize, ' '), "\t")
Console.WriteLine newLine
line <- Console.ReadLine()
// Recover the standard output stream so that a
// completion message can be displayed.
let standardOutput = new StreamWriter(Console.OpenStandardOutput())
standardOutput.AutoFlush <- true
Console.SetOut standardOutput
Console.WriteLine $"INSERTTABS has completed the processing of {args[0]}."
0
with :? IOException as e ->
let errorWriter = Console.Error
errorWriter.WriteLine e.Message
errorWriter.WriteLine usageText
1
Imports System.IO
Public Module InsertTabs
Private Const tabSize As Integer = 4
Private Const usageText As String = "Usage: INSERTTABS inputfile.txt outputfile.txt"
Public Function Main(args As String()) As Integer
If args.Length < 2 Then
Console.WriteLine(usageText)
Return 1
End If
Try
' Attempt to open output file.
Using writer As New StreamWriter(args(1))
Using reader As New StreamReader(args(0))
' Redirect standard output from the console to the output file.
Console.SetOut(writer)
' Redirect standard input from the console to the input file.
Console.SetIn(reader)
Dim line As String = Console.ReadLine()
While line IsNot Nothing
Dim newLine As String = line.Replace("".PadRight(tabSize, " "c), ControlChars.Tab)
Console.WriteLine(newLine)
line = Console.ReadLine()
End While
End Using
End Using
Catch e As IOException
Dim errorWriter As TextWriter = Console.Error
errorWriter.WriteLine(e.Message)
errorWriter.WriteLine(usageText)
Return 1
End Try
' Recover the standard output stream so that a
' completion message can be displayed.
Dim standardOutput As New StreamWriter(Console.OpenStandardOutput())
standardOutput.AutoFlush = True
Console.SetOut(standardOutput)
Console.WriteLine($"INSERTTABS has completed the processing of {args(0)}.")
Return 0
End Function
End Module
注解
该方法 ReadLine 从标准输入流中读取一行。 (有关行的定义,请参阅以下列表后面的段落。这意味着:
如果标准输入设备是键盘,方法 ReadLine 将阻止,直到用户按下 Enter 键。
该方法的最常见用途 ReadLine 之一是在清除控制台并显示新信息之前暂停程序执行,或提示用户在终止应用程序之前按 Enter 键。 下面的示例对此进行了演示。
using System; public class Example { public static void Main() { Console.Clear(); DateTime dat = DateTime.Now; Console.WriteLine("\nToday is {0:d} at {0:T}.", dat); Console.Write("\nPress any key to continue... "); Console.ReadLine(); } } // The example displays output like the following: // Today is 10/26/2015 at 12:22:22 PM. // // Press any key to continue...open System Console.Clear() let dat = DateTime.Now printfn $"\nToday is {dat:d} at {dat:T}." printf "\nPress any key to continue... " Console.ReadLine() |> ignore // The example displays output like the following: // Today is 12/28/2021 at 8:23:50 PM. // // Press any key to continue...Module Example Public Sub Main() Console.Clear() Dim dat As Date = Date.Now Console.WriteLine() Console.WriteLine("Today is {0:d} at {0:T}.", dat) Console.WriteLine() Console.Write("Press any key to continue... ") Console.ReadLine() End Sub End Module ' The example displays output like the following: ' Today is 10/26/2015 at 12:22:22 PM. ' ' Press any key to continue...如果标准输入重定向到文件,该方法 ReadLine 将从文件中读取一行文本。 例如,下面是一个名为 ReadLine1.txt的文本文件:
This is the first line. This is the second line. This is the third line. This is the fourth line.以下示例使用 ReadLine 该方法读取从文件重定向的输入。 当方法返回
null时,读取操作将终止,这表示没有要读取的行。using System; public class Example { public static void Main() { if (!Console.IsInputRedirected) { Console.WriteLine("This example requires that input be redirected from a file."); return; } Console.WriteLine("About to call Console.ReadLine in a loop."); Console.WriteLine("----"); String s; int ctr = 0; do { ctr++; s = Console.ReadLine(); Console.WriteLine("Line {0}: {1}", ctr, s); } while (s != null); Console.WriteLine("---"); } } // The example displays the following output: // About to call Console.ReadLine in a loop. // ---- // Line 1: This is the first line. // Line 2: This is the second line. // Line 3: This is the third line. // Line 4: This is the fourth line. // Line 5: // ---open System if not Console.IsInputRedirected then printfn "This example requires that input be redirected from a file." printfn "About to call Console.ReadLine in a loop." printfn "----" let mutable s = "" let mutable i = 0 while s <> null do i <- i + 1 s <- Console.ReadLine() printfn $"Line {i}: {s}" printfn "---" // The example displays the following output: // About to call Console.ReadLine in a loop. // ---- // Line 1: This is the first line. // Line 2: This is the second line. // Line 3: This is the third line. // Line 4: This is the fourth line. // Line 5: // ---Module Example Public Sub Main() If Not Console.IsInputRedirected Then Console.WriteLine("This example requires that input be redirected from a file.") Exit Sub End If Console.WriteLine("About to call Console.ReadLine in a loop.") Console.WriteLine("----") Dim s As String Dim ctr As Integer Do ctr += 1 s = Console.ReadLine() Console.WriteLine("Line {0}: {1}", ctr, s) Loop While s IsNot Nothing Console.WriteLine("---") End Sub End Module ' The example displays the following output: ' About to call Console.ReadLine in a loop. ' ---- ' Line 1: This is the first line. ' Line 2: This is the second line. ' Line 3: This is the third line. ' Line 4: This is the fourth line. ' Line 5: ' ---将示例编译为名为 ReadLine1.exe的可执行文件后,可以从命令行运行它,以读取文件的内容并将其显示到控制台。 语法为:
ReadLine1 < ReadLine1.txt
行定义为后跟回车符(十六进制0x000d)、换行符(十六进制0x000a)或属性的值的 Environment.NewLine 序列。 返回的字符串不包含终止字符(s)。 默认情况下,该方法从 256 个字符的输入缓冲区读取输入。 由于这包括 Environment.NewLine 字符(s),因此该方法可以读取最多包含 254 个字符的行。 若要读取较长的行,请调用 OpenStandardInput(Int32) 该方法。
该方法 ReadLine 同步执行。 也就是说,在读取行或 按 Ctrl+Z 键盘组合(后跟 Windows 上的 Enter )之前,它会阻止它。 该 In 属性返回一个 TextReader 对象,该对象表示标准输入流,并且同时具有同步 TextReader.ReadLine 方法和异步 TextReader.ReadLineAsync 方法。 但是,当用作控制台的标准输入流时,同步 TextReader.ReadLineAsync 执行而不是异步执行,并且仅在读取操作完成后返回 Task<String> 。
如果此方法引发 OutOfMemoryException 异常,则方法能够读取的字符数会高级读取器在基础 Stream 对象中的位置,但已读入内部 ReadLine 缓冲区的字符将被丢弃。 由于无法更改流中读取器的位置,因此已读取的字符不可恢复,并且只能通过重新初始化来 TextReader访问。 如果流中的初始位置未知或流不支持查找, Stream 则基础还需要重新初始化。 为了避免这种情况并生成可靠的代码,应使用 KeyAvailable 属性和 ReadKey 方法并将读取字符存储在预分配的缓冲区中。
如果在从控制台读取输入时按下 Ctrl+Z 组合键(后跟 Windows 上的 Enter ),该方法将 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
//
// >
open System
printfn "Enter one or more lines of text (press CTRL+Z to exit):\n"
let mutable line = ""
while line <> null do
printf " "
line <- Console.ReadLine()
if line <> null then
printfn $" {line}"
// 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
//
// >
Module Example
Public Sub Main()
Dim line As String
Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):")
Console.WriteLine()
Do
Console.Write(" ")
line = Console.ReadLine()
If line IsNot Nothing Then Console.WriteLine(" " + line)
Loop While line IsNot Nothing
End Sub
End Module
' 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
'
' >