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 표준 입력 스트림에서 줄을 읽습니다. 줄 정의는 다음 목록 뒤의 단락을 참조하세요. 즉, 다음을 의미합니다.

  • 디바이스가 있는 경우 표준 입력 키보드를 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
    

줄은 문자 시퀀스 뒤에 캐리지 리턴(16진수 0x000d), 줄 바꿈(16진수 0x000a) 또는 속성 값 Environment.NewLine 으로 정의됩니다. 반환된 문자열에는 종료 문자가 포함되지 않습니다. 기본적으로 메서드는 256자 입력 버퍼에서 입력을 읽습니다. 여기에는 문자가 Environment.NewLine 포함되므로 메서드는 최대 254자를 포함하는 줄을 읽을 수 있습니다. 긴 줄을 읽으려면 메서드를 호출합니다 OpenStandardInput(Int32) .

메서드는 ReadLine 동기적으로 실행됩니다. 즉, 줄을 읽거나 Ctrl+Z 키보드 조합(Windows에서 Enter )을 누를 때까지 차단됩니다. 속성은 In 표준 입력 스트림을 나타내고 동기 메서드와 비동 TextReader.ReadLineTextReader.ReadLineAsync 기 메서드를 모두 포함하는 개체를 반환 TextReader 합니다. 그러나 콘솔의 표준 입력 스트림으로 사용되는 경우 는 TextReader.ReadLineAsync 비동기식이 아닌 동기적으로 실행되고 읽기 작업이 완료된 후에만 를 Task<String> 반환합니다.

이 메서드가 예외를 OutOfMemoryException throw하는 경우 기본 Stream 개체의 판독기 위치는 메서드가 읽을 수 있는 문자 수만큼 고급이지만 내부 ReadLine 버퍼로 이미 읽은 문자는 삭제됩니다. 스트림에서 판독기의 위치를 변경할 수 없으므로 이미 읽은 문자는 복구할 수 없으며 를 다시 초기화 TextReader해야만 액세스할 수 있습니다. 스트림 내의 초기 위치를 알 수 없거나 스트림이 검색을 지원하지 않는 경우 기본 Stream 위치도 다시 초기화해야 합니다. 이러한 상황을 방지하고 강력한 코드를 생성하려면 속성과 ReadKey 메서드를 KeyAvailable 사용하고 미리 할당된 버퍼에 읽기 문자를 저장해야 합니다.

메서드가 콘솔에서 입력을 읽을 때 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
'       
'       >

적용 대상

추가 정보