我在C#中有一个应用程序,我得到了这个例外
System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo)
尝试任何单个数字字符串Convert.ToInt32
这是我的代码:
Console.Write("Enter IP : ");
string ip = Console.ReadLine();
Console.Write("Enter port : ");
string port = Console.ReadLine();
Console.Write("Enter interval in MS : ");
string temp1 = Console.ReadLine();
TO = Convert.ToInt32(temp1);
Console.Write("Enter number of threads to use : ");
string temp2 = Console.ReadLine();
threads = Convert.ToInt32(temp2);
ipe1 = new IPEndPoint(IPAddress.Parse(ip), Convert.ToInt32(port));
我不知道发生了什么,所以任何建议都会有所帮助。 (我发布这个深夜,所以可能会被删除,然后在更好的时间重新询问)
答案 0 :(得分:1)
找到了解决方案:我有一个线程在背景中读取阻止输入的键:p,我的错误
static void toggleloop()
{
do
{
ConsoleKeyInfo key1 = Console.ReadKey();
if (key1.Key == ConsoleKey.F1 && loop == true && showstatsbool == true)
{
loop = false;
showstatsbool = false;
}
} while (true);
}
在所有形式的输入完成之前,不应该调用
答案 1 :(得分:0)
如果输入intiger
值作为输入,此代码将起作用。即使您在输入整数值之前或之后有空格,这也会失败(尝试使用Convert.ToInt32(temp1.Trim())
)。因此,您可以调用Int32.TryParse
方法。它返回Boolean
值,指示转换是成功还是失败。
int port;
IPAddress ip;
Console.Write("Enter IP : ");
while (!int.TryParse(Console.ReadLine(), out ip))
Console.Write("The value must be IP Address, try again: ");
Console.Write("Enter port : ");
while (!int.TryParse(Console.ReadLine(), out port))
Console.Write("The value must be of integer type, try again: ");
string port = Console.ReadLine();
Console.Write("Enter interval in MS : ");
while (!int.TryParse(Console.ReadLine(), out TO))
Console.Write("The value must be of integer type, try again: ");
Console.Write("Enter number of threads to use : ");
while (!int.TryParse(Console.ReadLine(), out threads))
Console.Write("The value must be of integer type, try again: ");
ipe1 = new IPEndPoint(ip, port);