Console.ReadLine メソッド

定義

標準入力ストリームから次の 1 行分の文字を読み取ります。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.

次の文字行の文字数が MaxValue を超えています。The number of characters in the next line of characters is greater than MaxValue.

次の例では、既存のテキストファイルの名前と出力を書き込むファイルの名前の2つのコマンドライン引数が必要です。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 メソッドを使用してファイル内の各行を読み取り、4つのスペースのすべてのシーケンスをタブ文字に置き換え、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 メソッドを使用する最も一般的な用途の1つは、コンソールをクリアして新しい情報を表示する前にプログラムの実行を一時停止すること、またはアプリケーションを終了する前に 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.

行は、文字のシーケンス (16 進数の 0x000d)、ラインフィード (16 進数の 0x000d)、または 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. ストリーム内の初期位置が不明な場合、またはストリームがシークをサポートしていない場合は、基になる 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 文字が押された場合、メソッドは nullを返します。If 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
'       
'       >

適用対象

こちらもご覧ください