这种事情,肯定是交给正则表达式是最好的啦
引用命名空间System.Text.RegularExpressions;
string str = Console.ReadLine();
Regex reg = new Regex("^\\d+$");//设置正则表达式 匹配所有字符都为数字
Match m = reg.Matches(str); //将匹配结果赋值给Match m
if(m.Success) //判断是否匹配成功
{
//是整数
}
else
{
//不是整数
}
现在一个do while循环里面,只有为整数时才跳出循环。
int a;
while (!int.TryParse(Console.ReadLine(),out a))
{
Console.WriteLine("请输入一个数字");
}
Console.WriteLine(a);
Console.ReadLine();
加入一句:
try
{
int num = int32.parse(srt.trim());
}
catch
{
str = "";
console.writeline("输入的数不为整数!");
}