C# Workshop – Input

Standard

Input

In the previous examples everything has been output to the Console but it is also possible to allow something to be Input from the Console.
To create a simple input example by using dotnetfiddle.net and entering the following:

using System;

public class Demo
{
	public static void Main()
	{
		string value = Console.ReadLine();
		Console.WriteLine(value);
	}
}

When Run in dotnetfiddle.net a “Prompt” will appear below the code window > and can then type anything there and end input by typing enter or return, this will then be output.
Another example is to enter a number to be used in a calculation by entering in to dotnetfiddle.net the following:

using System;

public class Demo
{
	public static void Main()
	{
		int a = int.Parse(Console.ReadLine());
		int b = int.Parse(Console.ReadLine());
		Console.WriteLine(a + b);
	}
}

By typing in a value for a or b can then output the sum of these values, another feature shown is that types often have static Methods, in this case Parse which allows something to be converted to that type so when Run in dotnetfiddle.net you can enter 1 then 2 to get the answer 3, it’s possible to change the operator to ones used for int such as * for multiply, for subtraction or / for divide – for that last one try changing int to double to avoid losing anything after a decimal point like when doing 5 divided by 2.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s