Tutorial: 11 - Handling User Input in C#
In C#, like other programming languages, you can take input from user for processing it.
C# provides three methods for taking input from user in Console Applications.
Console.Read()
It reads characters from input stream and then returns respective ASCII value. Also keep in mind that return type will be integer as ASCII is stored using integer data type. See following snippet:
int i = Console.Read(); // Input: 6
Console.WriteLine(i); // Output: 54
Console.ReadLine()
It reads all characters from input stream till user presses Enter from keyboard and returns a string. See following snippet:
string s = Console.ReadLine(); // Input: Hello
Console.WriteLine(s); // Output: Hello
Since readline returns a string when you want to perform on integer or floating point values you will need to Cast string into respective data type:
int i;
i = Convert.ToInt32(Console.ReadLine()); // Input: 12
Console.WriteLine(i); // Output: 12
double d;
d = Convert.ToDouble(Console.ReadLine()); // Input: 1.2 Console.WriteLine(d); // Output: 1.2
Console.ReadKey()
It reads the character input by the user and returns its name. See following snippet:
ConsoleKeyInfo k = Console.ReadKey(); // Input: a
Console.WriteLine(k.KeyChar); // Output: a
Console.WriteLine(k.Key); // Output: A
Console.WriteLine(k.Key); // Output: A
No comments:
Post a Comment