Console.ReadLine 方法

定义

从标准输入流读取下一行字符。Reads the next line of characters from the standard input stream.

public:
 static System::String ^ ReadLine();
public static string ReadLine ();
static member ReadLine : unit -> string
Public Shared Function ReadLine () As String

返回

输入流中的下一行字符;如果没有更多的可用行,则为 nullThe 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 的文本文件: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 的可执行文件后,可以从命令行使用语法来运行该示例。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.NewLine 属性的值。A 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. 返回的字符串不包含终止字符。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. 由于读取器在流中的位置不能更改,已读取的字符不可恢复,只能通过重新初始化 TextReader来访问。Since 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. 如果流中的初始位置未知或流不支持查找,则还需要重新初始化基础 StreamIf 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
'       
'       >

适用于

另请参阅