Actually I'm trying to write small program that read input from user to decide whether is it integer
or not.
object x=Console.ReadLine();
check(x);
static void check(object x)
{
if (x.GetType() == typeof(int))
Console.WriteLine("int");
else
Console.WriteLine("not int");
}
You can use this:
string x = Console.ReadLine();
int i;
if(int.TryParse(x, out i))
Console.WriteLine("int");
else
Console.WriteLine("not int");
If the TryParse()
returns true
, the parsed value is stored in i
Just use Int.TryParse as in this example
int result;
string x = Console.ReadLine();
if(int.TryParse(x, out result))
Console.WriteLine("int");
else
Console.WriteLine("not int");
The method accepts the input string and an integer variable. If the string can be converted to an integer number, then the integer variable is initialized with the converted string and the method returns true. Otherwise the method returns false and the integer variable passed will be set to zero.
As a side note. Console.ReadLine returns a string
try
static void check()
{ int result
string x = Console.ReadLine();
if(int.TryParse(x, out result)
Console.WriteLine("int");
else
Console.WriteLine("not int");
}
Try this
int isInteger;
Console.WriteLine("Input Characters: ");
string x = Console.ReadLine();
if(int.TryParse(x, out isInteger)
Console.WriteLine("int");
else
Console.WriteLine("not int");
Console.ReadLine()
Will Always Return String . So you can Try Int.TryParse()
To Check the type. Check the bellow Example
int output;
string x = Console.ReadLine();
if(int.TryParse(x, out output)
Console.WriteLine("int");
else
Console.WriteLine("not int");
hope This may helpful for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.