Hoger
Hoger

Reputation: 63

check for valid number input - console application

I have a little problem with a simple console application in which i would like to detect if the user inputs a correctly formatted numerical value. That is, values such as 1212sss or anything like asjkq12323 or a single character is not accepted. I would like to only accept pure integer values.

Here is what i have tried

bool detectNumber(string s)
{
   int value=0;
   Int.TryParse(s,out value);
   return (value!=0)?true:false;
}

I appreciate any help. Thank you soooo much,,,,,

Upvotes: 0

Views: 5963

Answers (5)

Tim M.
Tim M.

Reputation: 54359

TryParse returns a boolean. Check that, not the value passed via the out parameter.

if( int.TryParse( s, out value ) )
{
  // do something
}

Or just:

return int.TryParse( s, out value );

Incidentally, it is not necessary to initialize a value passed using the out keyword. The method declaring the parameter must initialize it before returning.

int foo; // legal
int.TryParse( "123", out foo );

All BCL "Try" methods follow the same convention (such as double.TryParse() for floating point numbers, as @gdoron mentioned in the comments).

And for the curious, source code for the underlying library which implements int.TryParse().

Upvotes: 3

Abbas
Abbas

Reputation: 14432

Your code works normal, you can only refactor it a bit. Following code is shorter but does exactly the same:

static bool IsInt32(string s)
{
    int value;
    return Int32.TryParse(s, out value);
}

Upvotes: 0

balexandre
balexandre

Reputation: 75073

There are several ways to test for only numeric numbers:

first of all, never use Int because of it's maximum value, either use int or Int32.

Parse

int result;
if (int.TryParse("123", out result))
{
    Debug.WriteLine("Valid integer: " + result);
}
else
{
    Debug.WriteLine("Not a valid integer");
}

Convert.ToInt32()

// throws ArgumentNullExceptionint
result1 = Int32.Parse(null);

// doesn't throw an exception, returns 0
int result2 = Convert.ToInt32(null);

IsNumeric()

using Microsoft.VisualBasic;
// ......
bool result = Information.IsNumeric("123");

Pattern Matching

string strToTest = "123";
Regex reNum = new Regex(@"^\d+$");
bool isNumeric = reNum.Match(strToTest).Success;

Upvotes: 1

ionden
ionden

Reputation: 12776

string line = Console.ReadLine(); 
int value;
if (int.TryParse(line, out value)) 
{
    Console.WriteLine("Integer here!");
}
else
{
    Console.WriteLine("Not an integer!");
}

Upvotes: 1

juergen d
juergen d

Reputation: 204746

int value = 0;
bool ok = int.TryParse(s, out value);
return ok;

Upvotes: 2

Related Questions