-4

I have a problem on one website. On the website you get tasks to program. Then you upload it on and it runs the program.

I don't know what is wrong but I get this error:

Unhandled Exception: System.FormatException: Input string was not in the correct format

at System.Int32.Parse (System.String s) [0x00000] in <filename unknown>:0
at System.Convert.ToInt32 (System.String value) [0x00000] in <filename unknown>:0
at ImePrim.Program.Main () [0x00000] in <filename unknown>:0

My code:

namespace ImePrim
{
    class Program
    {
        static void Main()
        {
            int num1;
            int num2;
            float answer;

            num1 = Convert.ToInt32(Console.ReadLine());
            num2 = Convert.ToInt32(Console.ReadLine());

            answer = num1 + num2;

            Console.Write(answer);
        }
    }
}

If anyone knows how to fix thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    I don't know what your website does at `Console.ReadLine`, but obviously the returned string cannot be parsed into an `Int32`. – René Vogt May 15 '16 at 15:01
  • What are the lines of input being provided to your program? The error means that one of the lines could not be converted to an integer. – Phil Ross May 15 '16 at 15:02
  • Try something like `if (int.TryParse(Console.ReadLine(), out num1)) { Console.WriteLine("num1 is OK"); } else { Console.WriteLine("Bad num1 entered, using 0 instead."); }` – Jeppe Stig Nielsen May 15 '16 at 16:13

2 Answers2

0

I think numbers are space-separated, not new-line-separated.

Also you are reading two ints, but writing sum as float - why? Are the numbers really ints?

The site shows exception to you, so you can catch the exception and throw other one with string passed to Convert in it's Message.

Qwertiy
  • 19,681
  • 15
  • 61
  • 128
0

The code runs fine if you use whole numbers as input, but as soon as you put non-numeric characters in an input it will break with the exception you are receiving. Because integers are whole numbers, decimal points and commas will break your project too. To resolve it, simply wrap your code within a try-catch block, and have a look at the MSDN docs on how to handle exceptions.

Drew Kennedy
  • 4,118
  • 4
  • 24
  • 34