Export (0) Print
Expand All

Console::ReadLine Method

Updated: October 2008

Reads the next line of characters from the standard input stream.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

[HostProtectionAttribute(SecurityAction::LinkDemand, UI = true)]
public:
static String^ ReadLine()

Return Value

Type: System::String
The next line of characters from the input stream, or nullptr if no more lines are available.

ExceptionCondition
IOException

An I/O error occurred.

OutOfMemoryException

There is insufficient memory to allocate a buffer for the returned string.

ArgumentOutOfRangeException

The number of characters in the next line of characters is greater than Int32::MaxValue.

NoteNote:

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: UI. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

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).

If this method throws OutOfMemoryException, the reader's position in the underlying Stream 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. 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. If the initial position within the stream is unknown or the stream does not support seeking, the underlying Stream also needs to be reinitialized.

To avoid such a situation and produce robust code you should use the Read method and store the read characters in a preallocated buffer.

If the CTRL+Z character is pressed when the method is reading input from the console, the method returns nullptr. 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 
//        
//       >}

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. 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;
}

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Date

History

Reason

October 2008

Expanded the Remarks section and explained the example in greater detail.

Customer feedback.

Community Additions

ADD
Show:
© 2014 Microsoft