To read input as an integer in C#, use the Convert.ToInt32() method.
res = Convert.ToInt32(val);
Let's see how -
Convert.ToInt32 Converts the specified string representation of a number to an equivalent 32-bit signed integer.
First, read the console input -
string val; val = Console.ReadLine();
After reading, convert it to an integer.
int res; res = Convert.ToInt32(val);
Let’s see an example -
Live Demonstration
using System; using System.Collections.Generic; class Demo { static void Main() { string val; int res; Console.WriteLine("Input from user: "); val = Console.ReadLine(); // convert to integer res = Convert.ToInt32(val); // display the line Console.WriteLine("Input = {0}", res); } }
Input from user: Input = 0
The following is the output. Input is entered by the user.
Input from user: 2 Input = 2
The above is the detailed content of How to read input as integer in C#?. For more information, please follow other related articles on the PHP Chinese website!