Console.ReadLine 方法

定義

從標準輸入資料流讀取下一行字元。

public:
 static System::String ^ ReadLine();
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static string? ReadLine ();
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
public static string? ReadLine ();
public static string ReadLine ();
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member ReadLine : unit -> string
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("android")>]
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 namespace System;
using namespace System::IO;

int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   const int tabSize = 4;
   String^ usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
   StreamWriter^ writer = nullptr;
   if ( args->Length < 3 )
   {
      Console::WriteLine( usageText );
      return 1;
   }

   try
   {
      // Attempt to open output file.
      writer = gcnew StreamWriter( args[ 2 ] );
      // 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( gcnew StreamReader( args[ 1 ] ) );
   }
   catch ( IOException^ e ) 
   {
      TextWriter^ errorWriter = Console::Error;
      errorWriter->WriteLine( e->Message );
      errorWriter->WriteLine( usageText );
      return 1;
   }

   String^ line;
   while ( (line = Console::ReadLine()) != nullptr )
   {
      String^ newLine = line->Replace( ((String^)"")->PadRight( tabSize, ' ' ), "\t" );
      Console::WriteLine( newLine );
   }

   writer->Close();
   
   // Recover the standard output stream so that a 
   // completion message can be displayed.
   StreamWriter^ standardOutput = gcnew StreamWriter( Console::OpenStandardOutput() );
   standardOutput->AutoFlush = true;
   Console::SetOut( standardOutput );
   Console::WriteLine( "INSERTTABS has completed the processing of {0}.", args[ 1 ] );
   return 0;
}
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 會從標準輸入資料流程讀取一行。 (如需行的定義,請參閱下列 list.) 後面的段落這表示:

  • 如果標準輸入設備是鍵盤,方法 ReadLine 會封鎖直到使用者按下 Enter 鍵為止。

    方法最常見的用法 ReadLine 之一是先暫停程式執行,再清除主控台並顯示新的資訊,或提示使用者在終止應用程式之前按下 Enter 鍵。 下列範例將說明這點。

    using namespace System;
    
    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...
    
    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 字元 () ,所以 方法可以讀取最多包含 254 個字元的行。 若要讀取較長的 OpenStandardInput(Int32) 行,請呼叫 方法。

方法 ReadLine 會以同步方式執行。 也就是說,它會封鎖直到讀取一行或 按下 Ctrl+Z 鍵盤組合 (接著 Windows) 的 Enter 。 屬性會 InTextReader 回 物件,表示標準輸入資料流程,而且同時具有同步 TextReader.ReadLine 方法和非同步 TextReader.ReadLineAsync 方法。 不過,當做主控台的標準輸入資料流程使用時,會 TextReader.ReadLineAsync 以同步方式執行,而不是以非同步方式執行,而且只有在讀取作業完成之後才會傳 Task<String> 回 。

如果這個方法擲回 OutOfMemoryException 例外狀況,則基礎 Stream 物件中的讀取器位置會由方法能夠讀取的字元數進階,但已讀入內部 ReadLine 緩衝區的字元會被捨棄。 由於無法變更資料流程中的讀取器位置,因此無法復原已經讀取的字元,而且只能藉由重新初始化 TextReader 來存取。 如果資料流程內的初始位置未知或資料流程不支援搜尋,則基礎 Stream 也必須重新初始化。 若要避免這種情況並產生健全的程式碼,您應該使用 KeyAvailable 屬性和 ReadKey 方法,並將讀取字元儲存在預先配置的緩衝區中。

如果 Ctrl+Z 按鍵組合 (後面接著 Windows 上的 Enter) 在方法從主控台讀取輸入時按下,此方法會傳 null 回 。 這可讓使用者在迴圈中呼叫 方法時 ReadLine 防止進一步的鍵盤輸入。 下列範例會說明此情節。

using namespace System;

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 != nullptr) 
         Console::WriteLine("      " + line);
   } while (line != nullptr);   
}
// 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
//       
//       >}
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
'       
'       >

適用於

另請參閱