[英]Convert string to int C# and place to the array
我将字转换为整数有一个问题。 它写得不好吗?
foreach (string line in lines)
{
string[] words = line.Split(' ');
foreach (string word in words)
{
{
tab[i] = Int32.Parse(word);
Console.WriteLine(tab[i]);
i++;
}
}
}
在这些行上:
tab[i] = Int32.Parse(word);
我有错误:
mscorlib.dll中发生了'System.FormatException'类型的未处理异常
文件:
0
12 0
19 15 0
31 37 50 0
22 21 36 20 0
17 28 35 21 25 0
您的字符串不代表整型。 可能是一个带小数位的数字? (例如5.5?)要捕获并打印单词,您可以使用try / catch。
这意味着您的输入有问题。 考虑使用Int.TryParse,它会在您只想使用格式良好的整数的情况下起作用。 您还可以在失败时收集一些输出,以了解哪些值无法解析,例如,
bool b;
int tempNumber;
foreach (string line in lines)
{
string[] words = line.Split(' ');
foreach (string word in words)
{
b = Int32.TryParse(word, out tempNumber);
if (b) // success
{
tab[i] = tempNumber;
Console.WriteLine(tab[i]);
i++;
}
else // handle error
{
Console.WriteLine("Error: '" + word + "' could not be parsed as an Int32");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.