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.