0

What I am trying to achieve is write a very simple console program that continuously asks the user to enter a number or "ok" if he wants to exit. When he enters ok, the sum of all the previously entered numbers (integers) is shown inside the console. This is the code:

class Program
    {
        static void Main(string[] args)
        {
            int sum = 0;
            while (true)
            {
                Console.WriteLine("Please enter a number. Or \"Ok\" if you want to exit.");
                if (Console.ReadLine().ToLower() == "ok")
                {
                    Console.WriteLine(sum);
                    break;
                }
                else
                {
                    var s1 = Console.ReadLine();
                    sum += int.Parse(s1.Trim('\r', '\n'));
                }
            }
         }
    }

From similar questions on stackoverflow I understood that the string obtained through Console.Readline(), as long as we pass the number in (no letters etc.), should be easily converted to int with int.Parse. However, with the code above I get a System.FormatException: input string not in the correct format. The same happens when not using the Trim() method.

vinn23
  • 39
  • 4
  • 4
    You really don't want to use this: `if (Console.ReadLine().ToLower() == "ok")`. This will **eat** that line, and stop if you're entering ok, but you will not get that line in your int.parse context. You're going to have to enter a number twice to get it added to the sum, first to circumvent the ok-check, and second for the int.Parse. Instead grab it into a variable before the if-statements, and use the `s1` variable in both the ok-check and int.Parse – Lasse V. Karlsen Apr 26 '21 at 13:42
  • Also, `Console.ReadLine` does not include `\r` or `\n`, so that trim function is not necessary. – Lasse V. Karlsen Apr 26 '21 at 13:42
  • Yep, so if ok is entered on an odd line - you will be fine. But on an even it will blow up, like @LasseV.Karlsen explained. – mjwills Apr 26 '21 at 13:44
  • Also `Console.ReadLine` can return `null` - so use `?.ToLower()` rather than `ToLower` (or use `String.Compare`). – mjwills Apr 26 '21 at 13:45
  • You can get all sorts of garbage besides digits. Use TryParse instead. – Bob Provencher Apr 27 '21 at 03:55

0 Answers0