Console.ReadLine 方法

定義

從標準輸入資料流讀取下一行字元。Reads the next line of characters from the standard input stream.

public:
 static System::String ^ ReadLine();
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static string? ReadLine ();
public static string ReadLine ();
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
static member ReadLine : unit -> string
static member ReadLine : unit -> string
Public Shared Function ReadLine () As String

傳回

String

輸入資料流的下一行字元,或 null (如果沒有其他可用字行)。The next line of characters from the input stream, or null if no more lines are available.

屬性

例外狀況

發生 I/O 錯誤。An I/O error occurred.

沒有足夠記憶體可為傳回的字串配置緩衝區。There is insufficient memory to allocate a buffer for the returned string.

下一行字元中的字元數大於 MaxValueThe number of characters in the next line of characters is greater than MaxValue.

範例

下列範例需要兩個命令列引數:現有文字檔的名稱,以及要將輸出寫入其中的檔案名。The following example requires two command line arguments: the name of an existing text file, and the name of a file to write the output to. 它會開啟現有的文字檔,並將鍵盤的標準輸入重新導向至該檔案。It opens the existing text file and redirects the standard input from the keyboard to that file. 它也會將標準輸出從主控台重新導向至輸出檔案。It also redirects the standard output from the console to the output file. 然後,它會使用 Console.ReadLine 方法來讀取檔案中的每一行,以定位字元取代四個空格的每個序列,然後使用 Console.WriteLine 方法將結果寫入輸出檔。It then uses the Console.ReadLine method to read each line in the file, replaces every sequence of four spaces with a tab character, and uses the Console.WriteLine method to write the result to the output file.

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;
    }
}
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方法會從標準輸入資料流程讀取一行。The ReadLine method reads a line from the standard input stream. (行的定義,請參閱下列清單後面的段落。 ) 這表示:(For the definition of a line, see the paragraph after the following list.) This means that:

  • 如果標準輸入設備是鍵盤, ReadLine 方法會封鎖,直到使用者按下 Enter 鍵為止。If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key.

    方法最常見的用法之一, ReadLine 是在清除主控台和顯示新資訊之前暫停程式執行,或提示使用者在終止應用程式之前按下 enter 鍵。One of the most common uses of the ReadLine method is to pause program execution before clearing the console and displaying new information to it, or to prompt the user to press the Enter key before terminating the application. 下列範例將說明這點。The following example illustrates this.

    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...
    
    
    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 方法會從檔案讀取一行文字。If standard input is redirected to a file, the ReadLine method reads a line of text from a file. 例如,以下是名為 ReadLine1.txt 的文字檔:For example, the following is a text file named ReadLine1.txt:

    
    This is the first line.
    This is the second line.
    This is the third line.
    This is the fourth line.
    
    

    下列範例 ReadLine 會使用方法來讀取重新導向至檔案的輸入。The following example uses the ReadLine method to read input that is redirected from a file. 當方法傳回時,讀取作業 null 會終止,表示不會有任何行繼續讀取。The read operation terminates when the method returns null, which indicates that no lines remain to be read.

    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:
    //       ---
    
    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 的可執行檔之後,您可以從命令列使用語法來執行它。After compiling the example to an executable named ReadLine1.exe, you can run it from the command line with the syntax

    ReadLine1 < ReadLine1.txt
    

    以讀取檔案的內容,並將其顯示在主控台中。to read the contents of the file and display them to the console.

一行定義為字元序列,後面接著換行字元 (十六進位 0x000d) 、換行字元 (十六進位 0x000a) 或屬性的值 Environment.NewLineA line is defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or the value of the Environment.NewLine property. 傳回的字串不包含 (s) 的終止字元。The returned string does not contain the terminating character(s). 根據預設,方法會從256字元輸入緩衝區讀取輸入。By default, the method reads input from a 256-character input buffer. 因為這包含 Environment.NewLine) 的字元 (,所以方法可以讀取包含最多254個字元的行。Because this includes the Environment.NewLine character(s), the method can read lines that contain up to 254 characters. 若要讀取較長的行,請呼叫 OpenStandardInput(Int32) 方法。To read longer lines, call the OpenStandardInput(Int32) method.

方法會以 ReadLine 同步方式執行。The ReadLine method executes synchronously. 也就是說,它會封鎖直到讀取一行或按下 Ctrl + Z 鍵盤組合為止。That is, it blocks until a line is read or the Ctrl+Z keyboard combination is pressed. In屬性 TextReader 會傳回物件,該物件表示標準輸入資料流程,同時具有同步 TextReader.ReadLine 方法和非同步 TextReader.ReadLineAsync 方法。The In property returns a TextReader object that represents the standard input stream and that has both a synchronous TextReader.ReadLine method and an asynchronous TextReader.ReadLineAsync method. 不過,當當做主控台的標準輸入資料流程使用時,會以 TextReader.ReadLineAsync 同步方式執行,而不是以非同步方式執行,而且 Task<String> 只有在讀取作業完成後才會傳回。However, when used as the console's standard input stream, the TextReader.ReadLineAsync executes synchronously rather than asynchronously and returns a Task<String> only after the read operation has completed.

如果這個方法擲 OutOfMemoryException 回例外狀況,則讀取器在基礎物件中的位置 Stream 會由方法可以讀取的字元數進行前移,但已讀入內部緩衝區的字元會被 ReadLine 捨棄。If this method throws an OutOfMemoryException exception, the reader's position in the underlying Stream object is advanced by the number of characters the method was able to read, but the characters already read into the internal ReadLine buffer are discarded. 因為資料流程中讀取器的位置無法變更,所以已讀取的字元無法復原,而且只能藉由重新初始化來存取 TextReaderSince the position of the reader in the stream cannot be changed, the characters already read are unrecoverable, and can be accessed only by reinitializing the TextReader. 如果資料流程內的初始位置未知或資料流程不支援搜尋,則基礎 Stream 也需要重新初始化。If the initial position within the stream is unknown or the stream does not support seeking, the underlying Stream also needs to be reinitialized. 若要避免這種情況,並產生穩固的程式碼,您應該使用 KeyAvailable 屬性和 ReadKey 方法,並將讀取的字元儲存在預先配置的緩衝區中。To avoid such a situation and to produce robust code, you should use the KeyAvailable property and ReadKey method and store the read characters in a pre-allocated buffer.

如果在方法從主控台讀取輸入時按下 Ctrl + Z 字元,則方法會傳回 nullIf the Ctrl+Z character is pressed when the method is reading input from the console, the method returns null. 這可讓使用者 ReadLine 在迴圈中呼叫方法時,防止進一步的鍵盤輸入。This enables the user to prevent further keyboard input when the ReadLine method is called in a loop. 下列範例說明此案例。The following example illustrates this scenario.

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
//
//       >
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
'       
'       >

適用於

另請參閱