Reading Input From The Console

Lesson 5.1: Reading Input from the Console


Up until now, your programs have primarily displayed output to the user. In this lesson, you'll learn how to make your programs interactive by getting input from the user through the console.


The Console.ReadLine() Method


The Console.ReadLine() method is your key to reading user input in C#.

When this method is called, your program pauses and waits for the user to type something on the console and press the Enter key.

The text the user entered is then returned as a string value, which you can store in a variable and use in your program.

Example: Getting the User's Name


C#

using System;


class Program

{

    static void Main(string[] args)

    {

        Console.WriteLine("Please enter your name:"); 


        string name = Console.ReadLine(); // Get input and store it in 'name'


        Console.WriteLine("Hello, " + name + "!");

    }

}

Explanation:


Console.WriteLine("Please enter your name:");


This line displays a prompt to the user, asking them to enter their name.

string name = Console.ReadLine();


This line does the following:

Calls the Console.ReadLine() method, which waits for the user to type their name and press Enter.

The entered name is returned as a string and stored in the name variable.

Console.WriteLine("Hello, " + name + "!");


This line prints a greeting using the name entered by the user.

Reading Numeric Input


Console.ReadLine() returns a string, even if the user enters a number. To work with numeric input, you need to convert it.

Use the int.Parse() method to convert a string to an integer, or double.Parse() for floating-point numbers.

C#

Console.WriteLine("Enter your age:");

string input = Console.ReadLine();

int age = int.Parse(input);


Console.WriteLine("You are " + age + " years old.");


Error Handling


If the user enters something that can't be converted to the desired data type (e.g., letters instead of numbers), int.Parse() and double.Parse() will throw a FormatException.

You can use try-catch blocks to handle this gracefully:

C#

try

{

    age = int.Parse(input);

}

catch (FormatException)

{

    Console.WriteLine("Invalid input. Please enter a number.");

}

Key Points


Console.ReadLine(): Gets text input from the user.

Convert string input to numbers using int.Parse() or double.Parse().

Handle invalid input using try-catch blocks.

Practice:


Write a program that asks the user for their name and age.

Calculate and display the year they were born.

Make sure to handle invalid input appropriately.

This exercise will help you solidify your understanding of reading input from the console and converting it to the correct data type.

Couse Syllabus