Getting Input from User / Keyboard in C#

Getting Input from User / Keyboard in C# – Learn how to get input from user / keyboard like int, string and double data types etc in C# program. Example of taking integer / string input using Console.ReadLine method in C#.

To get the input from user, we use predefined Console.ReadLine method.

  • Console.ReadLine-Read complete string including spaces.
  • Console.Read – reads a character and returns an ASCII integer value for the input character.
  • Console.ReadKey-reads a character and returns that character.

How to take integer input from user in C#

C# Code

/*
 * Example of Reading integer value from keyboard
 */
using System;
 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the integer:");
            
             //Use conversion functions to convert string to int
            int num =Convert.ToInt32( Console.ReadLine());

            Console.WriteLine("You Entered : " + num);
        }
    }

Reading a string input from User in C#

In this section, you will learn how to take string input using Console.ReadLine in C# program. To read a string / sentence from the user we use ReadLine method of Console class.

C# Code

/*--------------------------------------------
 * Example of Reading string from user
 */

using System;
 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the integer:");

            String name =Console.ReadLine();

            Console.WriteLine("You entered your name as " + name);
        }
    }

Output:
Enter Your Name:
Viswanath Annangi
You entered your name as Viswanath Annangi

Reading Two Integers input from user in C#

Below program read two integers from user one by one. It prompt user to integer first and second number. The program displays the sum of both numbers entered by user. It will display the output as below

Output:

Enter first integer:
20
Enter Second integer:
30
Sum :50

/*-----------------------------------------------------------
 * Example of Reading two integer value from keyboard in C#
 */

using System;
class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter first integer: ");

            int first = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter Second integer: ");

            int second = Convert.ToInt32(Console.ReadLine());

            // Get sum of both first and second number
            int sum = first + second;

            // Display the sum

            Console.WriteLine("Sum :" + sum);
        }
    }

Related Posts