#971 – Reading a Line of Input from the Console

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

971-001

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 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());

971-002

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #971 – Reading a Line of Input from the Console

  1. Pingback: Dew Drop – November 11, 2013 (#1664) | Morning Dew

Leave a comment