-1

I'm trying to convert the string n to an int called numar. I can run the program, but after I exit the console, it gives me this error:

"System.FormatException: 'Input string was not in a correct format.

It throws on the line containing int numar = Convert.ToInt32(n);. How would I fix this?

static void Main(string[] args)
{
    int res = 1;
    string n = "";
    while (n != "x")
    {
        n =  Console.ReadLine();
        int numar = Convert.ToInt32(n);
        res = res * numar;


    }
    Console.WriteLine(res);
}
Twenty
  • 5,234
  • 4
  • 32
  • 67
razvan
  • 7
  • 3
    There is an [int.TryParse](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=netframework-4.8) method that you can use to *try* to convert the `string` to an `int` without getting an exception if the conversion fails. – mm8 Feb 24 '20 at 15:44
  • 1
    Either add exception handling (try / catch) or use `int.TryParse` instead of `int.Parse`. Also check your logic. If the user enters `"x"` (your intent is to exit) but first you try to parse this value as a number what do you think the system should do? Is it correct to assume that a number was entered when the user could also have pressed `x` to exit? Finally should you trust the user input especially when you are not limiting that input? – Igor Feb 24 '20 at 15:45

2 Answers2

2
var isNum = int.TryParse(n, out intValue)
if (isNum) {
   res = res * intValue;
}
AlleXyS
  • 2,476
  • 2
  • 17
  • 37
0

Try this:

var numar = 0;
Int32.TryParse(n, out numar);
worldwildwebdev
  • 374
  • 4
  • 17