Monday, January 24, 2011

Testing for non-numeric input C #

Here is a problem that many programmers will encounter while programming. Testing weather a value is a number or anything other than. I found some rather strange ways of doing this, but to me, there is only one for sure way.


static void Main(string[] args)
        {
            double numbers = 0;
            double runningTotal = 0;

            //Prompts the user to enter the total number of numbers to avg
            Console.Write("How many numbers do you want to average?: ");

            //Saves the input
            uint input;

            //try to convert if not loop until it can convert
            while (!uint.TryParse(Console.ReadLine(), out input) || input <= 0)
            {
                Console.WriteLine("Incorrect input.....please try again!!\n");
                Console.Write("How many numbers do you want to average?: ");
            }
            //More code goes here

The TryParse method is a solid way to test this.  TryParse can be used in so many ways that can be very beneficial to anyone.

Take the time to search the web for more ways to use this method