#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

Advertisement

#969 – Creating a Simple Console Application

You’ll most often create applications that have some sort of user interface, e.g. web applications, Windows Store apps, or desktop applications.  You may also create components using C# that have no user interface at all, e.g. class libraries.

For testing purposes, however, it’s helpful to create a simple application that can read from or write to a console window.  The console window appears as a window with a dark background when you run the application.  It can display text one line at a time, or read text entered by the user.  As new text is added to the bottom of the window, earlier text scrolls off the top.

969-002

You create a console application using Visual Studio by selecting the Console Application template when creating a new project.

969-001

You read from or write to the console using methods in the Console class, e.g. ReadLine and WriteLine.

#7 – Reading and Writing from the Console

To read and write from the console, use Console.Read, Console.ReadLine, Console.Write, Console.WriteLine.

namespace ReadWriteConsole
{
    class Program
    {
        static void Main()
        {
            Console.Write("This ");
            Console.WriteLine("is all on one line.");
            Console.Write("Enter your name: ");
            string name = Console.ReadLine();
            Console.WriteLine(name);
            Console.Read();     // pause
        }
    }
}