0

我在 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));

我不知道发生了什么,所以任何建议都会有所帮助。(我在深夜发布,所以它可能会被删除,然后在更好的时间重新询问)

4

2 回答 2

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);
        }

在所有形式的输入完成之前不应调用

于 2013-09-03T03:53:54.820 回答
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);
于 2013-09-03T03:49:36.033 回答