Console.Read. This reads in characters from the console. It returns, as an integer, each value until a zero is reached. This signifies the end of the user's input.
Calling Read. Typically this method should be called in a loop to get all the buffered characters. But usually ReadLine or even ReadKey are better choices.
Example. We look at a console program written in the C# language. It is intended to demonstrate the exact behavior of the Console.Read method when used in a while-loop.
using System;
class Program
{
static void Main()
{
// This program accepts console input.// ... When the enter key is pressed,// the Read method returns the first time.// ... Then, each call to Read accesses one// further character from the input.
int result;
while ((result = Console.Read()) != 0)
{
Console.WriteLine("{0} = {1}", result, (char)result);
}
}
}dotnetperls
100 = d
111 = o
116 = t
110 = n
101 = e
116 = t
112 = p
101 = e
114 = r
108 = l
115 = s
13 =
10 =
Notes, Read. If you just need one character, skip the loop. Read does not return until the input is final and the user presses the enter key.
Tip For most programs that require strings from the terminal, please consider the Console.ReadLine method.
Summary. We applied Console.Read in a program that prints the terminal buffer contents. This method is normally used in a loop in console programs that can accept more than one character.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.