Console Input and output
Explains how user input and output is integrated in the C# program
Though we can assign values to the variables, most of the time we will need to get input from the user. We can use `Console.ReadLine' for this purpose. Here is a simple example:
string name; name=Console.ReadLine();
Here, a string variable `name' is declared. In the next statement, the Console.ReadLine will read the value entered by the user and store it in the variable `name'.
This is fine for string inputs. However, to input values such as integers or doubles, we need to adopt a slightly different approach because the resulting input from using Console.ReadLine is a text input and cannot be assigned to other types of variables. If we try to do this, the program will generate an error.
One solution to this situation is shown in this example:
int num; num=int.Parse(Console.ReadLine());
In this case, the resulting input from using Console.ReadLine is a string but `int.Parse' will convert it into integer and assign this value to the variable `num'. We can use a similar `double.Parse' to read values of type `double'.
Just as we use `Console.ReadLine' to read values, we can use `Console.WriteLine' to display messages and values stored in variables. We have already seen how to display a message using `Console.WriteLine' -
Console.WriteLine("Hello.Looks like my first application");
Here is a small program to illustrate the use of `Console.WriteLine' -
static void Main(string[] args) { int num;
Console.WriteLine("Enter a number"); num=int.Parse(Console.ReadLine()); Console.WriteLine("You have entered {0}", num); }
In this example, the first `Console.WriteLine' is used to display a simple message. In the second `Console.WriteLine' statement, we have used {0} with the message. This is known as a placeholder. When displaying the output, this placeholder will be replaced by the variable specified after the comma (,). In our case, the variable is `num'. So, if the user enters 10 as the input, the output message will be:
You have entered 10
To display the values of multiple variables, we use multiple placeholders. Consider another example:
static void Main(string[] args) { int num; string name;
Console.WriteLine("Enter your name"); name = Console.ReadLine();
Console.WriteLine("Now enter a number"); num=int.Parse(Console.ReadLine()); Console.WriteLine("Hello {0}, you have entered {1}", name,num); }
In this example, the last `Console.WriteLine' statement has two placeholders. When the output is displayed, the first placeholder {0} will be replaced by the value of the variable `name' and the second placeholder {1} will be replaced by the value stored in variable `num'.