Open E-School

Male
Friday, February 24, 1984

Console.Read() – Read character inputs from Console using C#

Category: Programming Date: Sunday, March 22, 2015

Goal – Read character by character input from Console using C#

Namespaces used

System ( Console class is defined in the System namespace )

Classes used

Console

Methods used

Console.Read() – Static method defined in the Console class

Brief description

Console.Read() method reads the next character entered by the user from the keyboard. It takes no arguments and returns the ASCII value of the key that is pressed by the user.

Code

using System;    namespace ConsoleApplication1  {      class Program      {          public static void Main(string[] args)          {              int userInput = 0;              char keyPressed;                Console.Write("Press any key and then hit enter : ");              userInput = Console.Read();                keyPressed = (char)userInput;                Console.WriteLine("The ASCII value of the key pressed by you is : " + userInput);              Console.WriteLine("The key pressed by you is : " + keyPressed);          }      }  }

Output

Console.Read() output
 
Explanation of the code

We have taken two variables in this program – one of the type int and the other of the type char. The int type variable is used to store the ASCII value of the key pressed which will be returned by the Console.Read() method. The char type variable is used to  typecaste the int value into char and then print the actual character pressed entered by the user. In the last two lines of code we have printed the int value of the key pressed as well as its character equivalent.

Special Remarks

Console.Read() method reads one character at a time whereas the Console.ReadLine() method reads one line at a time.

Rate this article and help us improve

Please Login to rate
Overall ratings: 0 | Rating: out of 5
Previous Article Next Article

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp