Console.ReadLine Método

Definición

Lee la siguiente línea de caracteres del flujo de entrada estándar.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

Devoluciones

String

La siguiente línea de caracteres del flujo de entrada o null si no hay más líneas disponibles.The next line of characters from the input stream, or null if no more lines are available.

Atributos

Excepciones

Error de E/S.An I/O error occurred.

No hay memoria suficiente para asignar un búfer para la cadena devuelta.There is insufficient memory to allocate a buffer for the returned string.

El número de caracteres de la siguiente línea de caracteres es mayor que MaxValue.The number of characters in the next line of characters is greater than MaxValue.

Ejemplos

El ejemplo siguiente requiere dos argumentos de la línea de comandos: el nombre de un archivo de texto existente y el nombre de un archivo en el que se va a escribir el resultado.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. Abre el archivo de texto existente y redirige la entrada estándar del teclado a ese archivo.It opens the existing text file and redirects the standard input from the keyboard to that file. También redirige la salida estándar de la consola de al archivo de salida.It also redirects the standard output from the console to the output file. A continuación, usa el Console.ReadLine método para leer cada línea del archivo, reemplaza cada secuencia de cuatro espacios por un carácter de tabulación y usa el Console.WriteLine método para escribir el resultado en el archivo de salida.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

Comentarios

El ReadLine método lee una línea del flujo de entrada estándar.The ReadLine method reads a line from the standard input stream. (Para ver la definición de una línea, vea el párrafo que aparece después de la lista siguiente). Esto significa que:(For the definition of a line, see the paragraph after the following list.) This means that:

  • Si el dispositivo de entrada estándar es el teclado, el ReadLine método se bloquea hasta que el usuario presiona la tecla entrar .If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key.

    Uno de los usos más comunes del ReadLine método consiste en pausar la ejecución del programa antes de borrar la consola y Mostrar información nueva, o bien para pedir al usuario que presione la tecla entrar antes de finalizar la aplicación.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. Esto se ilustra en el siguiente ejemplo: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...
    
  • Si la entrada estándar se redirige a un archivo, el ReadLine método lee una línea de texto de un archivo.If standard input is redirected to a file, the ReadLine method reads a line of text from a file. Por ejemplo, el siguiente es un archivo de texto denominado 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.
    
    

    En el ejemplo siguiente se usa el ReadLine método para leer la entrada que se redirige desde un archivo.The following example uses the ReadLine method to read input that is redirected from a file. La operación de lectura finaliza cuando el método devuelve null , lo que indica que no se va a leer ninguna línea.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:
    '       ---
    

    Después de compilar el ejemplo en un ejecutable denominado ReadLine1.exe, puede ejecutarlo desde la línea de comandos con la sintaxisAfter compiling the example to an executable named ReadLine1.exe, you can run it from the command line with the syntax

    ReadLine1 < ReadLine1.txt
    

    para leer el contenido del archivo y mostrarlos en la consola.to read the contents of the file and display them to the console.

Una línea se define como una secuencia de caracteres seguida de un retorno de carro (0x000d hexadecimal), un salto de línea (hexadecimal 0x000a) o el valor de la Environment.NewLine propiedad.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. La cadena devuelta no contiene los caracteres de terminación.The returned string does not contain the terminating character(s). De forma predeterminada, el método lee la entrada desde un búfer de entrada de 256 caracteres.By default, the method reads input from a 256-character input buffer. Como esto incluye los Environment.NewLine caracteres, el método puede leer líneas que contienen hasta 254 caracteres.Because this includes the Environment.NewLine character(s), the method can read lines that contain up to 254 characters. Para leer las líneas más largas, llame al OpenStandardInput(Int32) método.To read longer lines, call the OpenStandardInput(Int32) method.

El ReadLine método se ejecuta sincrónicamente.The ReadLine method executes synchronously. Es decir, se bloquea hasta que se lee una línea o se presiona la combinación de teclas Ctrl + Z.That is, it blocks until a line is read or the Ctrl+Z keyboard combination is pressed. La In propiedad devuelve un TextReader objeto que representa el flujo de entrada estándar y que tiene un método sincrónico TextReader.ReadLine y un TextReader.ReadLineAsync método asincrónico.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. Sin embargo, cuando se usa como el flujo de entrada estándar de la consola, se TextReader.ReadLineAsync ejecuta de forma sincrónica en lugar de asincrónica y devuelve un Task<String> solo después de que se haya completado la operación de lectura.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.

Si este método produce una OutOfMemoryException excepción, la posición del lector en el objeto subyacente Stream se avanza por el número de caracteres que el método puede leer, pero los caracteres ya leídos en el búfer interno ReadLine se descartan.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. Puesto que no se puede cambiar la posición del lector en la secuencia, los caracteres ya leídos son irrecuperables y solo se puede tener acceso a ellos reinicializando 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. Si se desconoce la posición inicial dentro de la secuencia o si la secuencia no admite búsquedas, el subyacente Stream también debe reinicializarse.If the initial position within the stream is unknown or the stream does not support seeking, the underlying Stream also needs to be reinitialized. Para evitar esta situación y generar código sólido, debe usar la KeyAvailable propiedad y el ReadKey método y almacenar los caracteres de lectura en un búfer asignado previamente.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.

Si se presiona el carácter Ctrl + Z cuando el método lee la entrada de la consola, el método devuelve null .If the Ctrl+Z character is pressed when the method is reading input from the console, the method returns null. Esto permite al usuario evitar más entradas de teclado cuando ReadLine se llama al método en un bucle.This enables the user to prevent further keyboard input when the ReadLine method is called in a loop. Este escenario se ilustra en el ejemplo siguiente.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
'       
'       >

Se aplica a

Consulte también