Serving Information Simply

Wednesday 23 January 2013

Reading data from keyword and basic Input/output in C#.Net


In this post I will show how to apply command-based input/output actions in C#.Net by using the Console class. Here you will see how to display information by using the Write and WriteLine methods, and how to collect input information from the keyboard by using the Read and ReadLine methods…..

Console Class in C#.Net
The Console class provides a C# application with access to the standard input, standard output, and standard error streams. Standard input is normally associated with the keyboard—anything that the user types on the keyboard can be read from the standard input stream. Similarly, the standard output stream is basically directed to the screen, as is the standard error stream.
Note:-
These streams and the Console class are only having a meaning to console applications. These are applications that run in a Command window.
Write and WriteLine Methods
You can use the Console.Write and Console.WriteLine methods to display information on the console screen in C# console programming.
Main difference is that WriteLine appends a new line/carriage return pair to the end of the output, and Write does not dot that. These Both methods are overloaded. You can call them with variable numbers and types of parameters.
For example, you can use the following code to write “100″ to the screen:
Console.WriteLine(100);
You can use the below code to write the message “I am Don of, World” to the screen:
Console.WriteLine(“I am Don of, World”);
Read and ReadLine Methods
You can get user input from the keyboard by using the Console.Read and Console.ReadLine methods.
The Read Method
According to the method named Read it reads the next character from the keyboard. It returns the int value –1 if there is no more input available. Otherwise it returns an int representing the character read.
The ReadLine Method
ReadLine reads all characters up to the end of the input line (the carriage return character). The input is returned as a string of characters. You can use the following code to read a line of text from the keyboard and display it to the screen:
string input = Console.ReadLine( );
Console.WriteLine(“{0}”, input);
Example…..
A sample program to input name and age of a person and check it to be valid voter.
using x=System.Console;
class Program
{
static void Main(string[] args)
{
x.Write("Name : ");
string name=x.ReadLine();
x.Write("Age : ");
int age=int.Parse(x.ReadLine());
if(age>=18)
x.WriteLine("Dear {0} you can vote",name);
else
x.WriteLine("Dear {0} you cannot vote",name);
}
}

Here To convert string kind of data to numeric kind of data we are using Parse () method of the corresponding data type.

More about parse keyword you will get into my next article.

Thanks …………………keep visiting…….:)



No comments:

Post a Comment