Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate console input as integers?

I have written my codes and i want to validate it in such a way thet it will only allow intergers to be inputed and not alphabets. Here is the code, please I will love you to help me. Thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace minimum
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = Convert.ToInt32(Console.ReadLine());
            int b = Convert.ToInt32(Console.ReadLine());
            int c = Convert.ToInt32(Console.ReadLine());

            if (a < b)
            {
                if (a < c)
                {
                    Console.WriteLine(a + "is the minimum number");
                }
            }
            if (b < a)
            {
                if (b < c)
                {
                    Console.WriteLine(b + "is the minimum number");
                }
            }
            if (c < a)
            {
                if (c < b)
                {
                    Console.WriteLine(c + "is the minimum number");
                }
            }


            Console.ReadLine();
        }
    }
}
like image 458
SIMI Avatar asked Jan 26 '11 13:01

SIMI


2 Answers

You should test if it's an int instead of converting in right away. Try something like :

string line = Console.ReadLine();
int value;
if (int.TryParse(line, out value))
{
   // this is an int
   // do you minimum number check here
}
else
{
   // this is not an int
}
like image 153
zov Avatar answered Sep 29 '22 22:09

zov


To get the console to filter out alphabetical keystrokes you have to take over input parsing. The Console.ReadKey() method is fundamental to this, it lets you sniff the pressed key. Here's a sample implementation:

    static string ReadNumber() {
        var buf = new StringBuilder();
        for (; ; ) {
            var key = Console.ReadKey(true);
            if (key.Key == ConsoleKey.Enter && buf.Length > 0) {
                return buf.ToString() ;
            }
            else if (key.Key == ConsoleKey.Backspace && buf.Length > 0) {
                buf.Remove(buf.Length-1, 1);
                Console.Write("\b \b");
            }
            else if ("0123456789.-".Contains(key.KeyChar)) {
                buf.Append(key.KeyChar);
                Console.Write(key.KeyChar);
            }
            else {
                Console.Beep();
            }
        }
    }

You could add, say, Decimal.TryParse() in the if() statement that detects the Enter key to verify that the entered string is still a valid number. That way you can reject input like "1-2".

like image 41
Hans Passant Avatar answered Sep 29 '22 21:09

Hans Passant