-1

I have a console app with an int variable. I need to read input from the user and be sure I can tell the user that they have entered an invalid answer if the input can't convert to an integer value.

How can I do this? Here is what I have so far:

class Program
{
    static void Main(string[] args)
    {
    Start:
        Console.WriteLine("Enter two numbers");
        var input1 = Convert.ToInt32(Console.ReadLine());
        var input2 = Convert.ToInt32(Console.ReadLine());
        if (input1 + input2 == 3)
            Console.WriteLine("");
        else if (input1 + input2 == 10)
        {
            Console.WriteLine("");
        }
        else
            Console.WriteLine("");
        goto Start;
    }
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794

3 Answers3

4

Convert.ToInt32(string) will throw exceptions, just as you mention, when the input cannot be parsed.

Instead, use int.TryParse(string, out var result).

In your code, it would be

if (!int.TryParse(Console.ReadLine(), out var input1 ||
    !int.TryParse(Console.ReadLine(), out var input2))
{
    Console.WriteLine("You did not enter integers.");
    goto Start;
}

You can read more about the method in the .NET documentation

P.s. By the way, you should avoid using goto in your code. But that's another matter.

Adam B
  • 506
  • 1
  • 5
  • 13
1

I would recommend using int.TryParse (documented here).

It will return false if the input is not an integer.

Ex:

int num1;
string input = Console.ReadLine();
if(!int.TryParse(input, out num1))
{
    Console.WriteLine("that's not a valid integer");
}
nick
  • 2,833
  • 3
  • 34
  • 61
-1

use regular expression, Regex is best for c# to check number format. look at this:

Regex for numbers only

Ali Mardan
  • 147
  • 5