Reputation: 103
using System;
using System.Text;
namespace 判断输入是否为数字
{
internal class Program
{
public static int ConsoleInputDigit(int length)
{
char[] news = new char[length];
for (int i = 0; i < news.Length; i++)
{
char temp = Console.ReadKey().KeyChar;
if (char.IsDigit(temp))
{
news[i] = temp;
}
else
{
Console.Write("\b \b");
i--;
}
}
return int.Parse(new string(news));
}
public static void Main(string[] args)
{
Console.Write("Input Year:");
int y = ConsoleInputDigit(4);
Console.Write("\nInput Month:");
int m = ConsoleInputDigit(2);
Console.Write("\nInput Day:");
int d = ConsoleInputDigit(2);
}
}
}
This ConsoleApp is suppose to input year、month、day from Console. I want to disable key except digital numbers(0-9).
Now this is my code, generally, it works.
But, for example, I want to input "2020" to year, when I input "202" and press Enter, the cursor will jump to the beginning of this line. It looks like the screenshot, Although it will not affect the final result.
I want to Console ignore the Enter key press(nothing happen), How to do that please?
Upvotes: 0
Views: 1333
Reputation: 179
This is how you can skip the enter key
internal class Program
{
public static int ConsoleInputDigit(int length)
{
char[] news = new char[length];
for (int i = 0; i < news.Length; i++)
{
var key = Console.ReadKey();
if (key.KeyChar.IsDigit(temp))
{
news[i] = temp;
}
else if(key == ConsoleKey.Enter)
{
// ignore
}
else
{
Console.Write("\b \b");
i--;
}
}
return int.Parse(new string(news));
}
public static void Main(string[] args)
{
Console.Write("Input Year:");
int y = ConsoleInputDigit(4);
Console.Write("\nInput Month:");
int m = ConsoleInputDigit(2);
Console.Write("\nInput Day:");
int d = ConsoleInputDigit(2);
}
}
Upvotes: 0