![](/img/trans.png)
[英]Int32.Parse(“356882”) generate exception System.FormatException: 'Input string was not in a correct format.'
[英]System.FormatException: Input string was not in a correct format from an int.Parse
try
{
for (int i = 0; i < 4; i++)
{
playerGuess[i] = int.Parse(Console.ReadLine()); //says this is the error
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught", ex);
Console.Read();
}
我运行此代码,由于某种原因,它输出以下错误:
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
at System.Convert.ToInt32(String value)
我尝试了我在另一个这样的线程上看到的修复,但我无法让它们工作。 有任何想法吗?
如果您提供的值无法转换为 int,则int.Parse()
将失败并出现异常到方法。
您可以使用int.TryParse()
代替,它通过返回指示成功的 boolean 使您可以更好地控制如何处理失败。 您可能会显示一条错误消息,并要求用户重新提交。
string input = Console.ReadLine();
int result;
if(int.TryParse(input, out result)) // TryParse returns a boolean showing whether the parse worked
{
// then perform your behavior safely
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.