
You want to apply the Console.Read method in the System namespace to your console program written in the C# language. The Console.Read method blocks until the input is received in full, and then can be called in a loop to get all the buffered characters.
This C# article demonstrates the use of the Console.Read method. It shows the output in a terminal window.
Initially here, we look at a console program written in the C# language that is intended to demonstrate the exact behavior of the Console.Read public static method when used in a while loop in a terminal window. When the Read method is first called, it blocks execution waiting for the input to be sent by the terminal window; it finally returns when the input is final. Then, you must call it in a loop to read the entire remaining buffer.
Program that uses Console.Read method [C#]
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);
}
}
}
Output
Enter is pressed after first line.
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 =
Description. In this program, we show the Console.Read method in the Main entry point method. The local integer variable with identifier "result" is used as an assignment in the loop condition. The conditional expression continues until the zero value is received from Console.Read, and this occurs at the very end of the input. The program outputs the integer representation and the character representation of each value in the buffer. The final two characters (13 and 10) are equal to the Windows newline.
We looked at the Console.Read method in the C# programming language and applied it in a program that prints the exact terminal buffer contents. This method is normally used in a loop in console programs that can accept more than one character; if you just need one character, you do not need the loop. It does not return until the input is final and the user presses the enter key. Finally, for most programs that require strings from the terminal, please consider the Console.ReadLine method, which constructs the string for you automatically.
Console.ReadLine Tips Console Programs