Friday, March 11, 2005

 

Console Input

Console IO is accomplished through the standard streams Console.In, Console.Out and Console.Error

Console.In
Console.In is an instance of TextReader. Console defines two input methods: Read() and ReadLine(). Read() returns the next character read from the console. It waits until the user presses a key and then returns the result. The character is returned as an int, which must be cast to char. Read() returns -1 on error or end of stream (one-past the last character). By default, console input is line-buffered, this means you must press Enter before any character will be sent to your program.

Read() Method
The Read() method is line-buffered. When you press Enter, a carriage-return (ASCII: 13), line-feed (ASCII:10) sequence are entered into the input stream. These characters are left-spending in the input until you read them.

This is a sample program that demonstrates this effect:
using System;
using System.IO;

class ConsoleInput
{
public static void Main()
{
char ch;
int chInt;

Console.WriteLine("To terminate this program, press F6 or Contol-Z");
Console.Write("Press any key followed by ENTER: ");

while( (chInt = Console.Read()) != -1 )
{
ch = (char) chInt;
Console.Write("You wrote: " );
if(! char.IsControl(ch) )
Console.WriteLine("\"{0}\"", ch );
else
Console.WriteLine( chInt );
}

}
}

Although Console’s methods are easiest way to read from Console.In, you can call methods on the underlying TextReader.

Here’s a program that does that:

using System;

class ReadTextReader
{
public static void Main()
{
string str;

Console.WriteLine("Enter some characters: ");
str = Console.In.ReadLine();

Console.WriteLine("You entered: \"{0}\"", str );
}
}


- End -
Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?