#971 – Reading a Line of Input from the Console
November 11, 2013 1 Comment
For testing purposes, you may create a simple console application that allows writing to and reading from a console window.
The Console.ReadLine method reads the next line’s worth of characters, storing the result in a string. The user can enter some text and then press the Enter key. When the user presses Enter, whatever they typed on that line is stored in a variable of type string.
while (true) { Console.Write(": "); string nextLine = Console.ReadLine(); Console.WriteLine("[{0}]", nextLine); }
You can also use the Console.Read method to read a single character. The characters are not read until the user presses Enter.
In the example below, the user types the letters a, and b and then presses Enter. The two calls to Console.Read are then executed, storing the ASCII values of the characters entered.
int char1 = Console.Read(); int char2 = Console.Read(); Console.Write("{0} {1}", char1.ToString(), char2.ToString());