Skip to content

Instantly share code, notes, and snippets.

@TheBrambleShark
Created February 12, 2019 19:52
Show Gist options
  • Select an option

  • Save TheBrambleShark/1885b737997fcd7f9e21485e6ccfeb57 to your computer and use it in GitHub Desktop.

Select an option

Save TheBrambleShark/1885b737997fcd7f9e21485e6ccfeb57 to your computer and use it in GitHub Desktop.
private static int ReadInt(int min = int.MinValue, int max = int.MaxValue)
{
StringBuilder sb = new StringBuilder();
do
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (char.IsNumber(key.KeyChar))
{
Console.Write(key.KeyChar);
sb.Append(key.KeyChar);
}
else if (key.Key == ConsoleKey.Backspace && sb.Length > 0)
{
Console.Write("\b \b");
sb.Length--;
}
else if (key.Key == ConsoleKey.Enter)
{
if (sb.Length > 0)
{
int num = int.Parse(sb.ToString());
if (num >= min && num <= max)
{
Console.WriteLine();
return num;
}
else
{
int line = Console.CursorTop;
int col = Console.CursorLeft;
Console.SetCursorPosition(0, line + 1);
Console.WriteLine($"Input must be between {min} and {max} inclusive");
Console.SetCursorPosition(col, line);
}
}
}
else
{
Console.Beep();
}
} while (true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment