Console.ReadLine Console.ReadLine Console.ReadLine Console.ReadLine Method

定義

標準入力ストリームから次の 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) {
        StreamWriter writer = null;

        if (args.Length < 2) {
            Console.WriteLine(usageText);
            return 1;
        }

        try {
            // Attempt to open output file.
            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(new StreamReader(args[0]));
        }
        catch(IOException e) {
            TextWriter errorWriter = Console.Error;
            errorWriter.WriteLine(e.Message);
            errorWriter.WriteLine(usageText);
            return 1;            
        }
        string line;
        while ((line = Console.ReadLine()) != null) {
            string newLine = line.Replace(("").PadRight(tabSize, ' '), "\t");
            Console.WriteLine(newLine);
        }
        writer.Close();
        // Recover the standard output stream so that a 
        // completion message can be displayed.
        StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
        standardOutput.AutoFlush = true;
        Console.SetOut(standardOutput);
        Console.WriteLine("INSERTTABS has completed the processing of {0}.", args[0]);
        return 0;
    }
}
Imports System.IO

Public Class InsertTabs
   Private Const tabSize As Integer = 4
   Private Const usageText As String = "Usage: INSERTTABS inputfile.txt outputfile.txt"
   
   Public Shared Function Main(args() As String) As Integer
      Dim writer As StreamWriter = Nothing

      If args.Length < 2 Then
         Console.WriteLine(usageText)
         Return 1
      End If
      
      Try
         ' Attempt to open output file.
         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(New StreamReader(args(0)))
      Catch e As IOException
         Dim errorWriter As TextWriter = Console.Error
         errorWriter.WriteLine(e.Message)
         errorWriter.WriteLine(usageText)
         Return 1
      End Try

      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
      writer.Close()
      ' 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 {0}.", args(0))
      Return 0
   End Function 
End Class

注釈

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.

行が文字の後にキャリッジ リターン (16 進数の 0x000d)、ライン フィード (16 進数の 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. ストリーム内の初期位置が不明またはストリームがシークを基になるをサポートしていない場合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
'       
'       >

適用対象

こちらもご覧ください