使用 Double for Decimals 时输入的字符串格式不正确
Input string not in correct format when using Double for Decimals
using System;
namespace FirstConsoleProject
{
class MainClass
{
public static void Main (string[] args)
{
Console.Write ("Please Put IP: ");
double userip = Convert.ToDouble (Console.ReadLine()); //Error Here <--- Input string not in correct format
Console.Write ("The User's IP is: " + userip);
Console.ReadKey ();
}
}
}
以前基本上是
int userip = Convert.ToInt32 (Console.ReadLine());
但我知道 IP 是小数,所以我尝试使用 Double,所以我输入
double userip = Convert.ToDouble (Console.ReadLine());
但现在问题是当我运行 使用"Double" 并输入类似1.1.1.1 的代码时,它显示"Input string was not in a correct format"。但是当我输入一个没有小数的整数时,比如 23 或 2,它起作用了......为什么?
Why?
因为 IP 地址不是 double
。这不是 甚至 一个数字。它是一种数字标签。仅包含一个带有一些数字的点并不能使其成为有效的双精度值(或任何数值)。
喜欢的可以IPAddress.Parse
or IPAddress.TryParse
解析
IP 地址不是十进制格式,请使用 IPAddress.Parse 或 TryParse
IPAddress userIp = IPAddress.Parse(Console.ReadLine);
https://msdn.microsoft.com/en-us/library/1b2h863h(v=vs.110).aspx
尝试使用正则表达式来匹配 IP 地址:
string userIP = Console.ReadLine();
Match match = Regex.Match(userIP, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");
if (match.Success)
{
Console.WriteLine("Valid IP");
}
else
{
Console.WriteLine("Invalid");
}
using System;
namespace FirstConsoleProject
{
class MainClass
{
public static void Main (string[] args)
{
Console.Write ("Please Put IP: ");
double userip = Convert.ToDouble (Console.ReadLine()); //Error Here <--- Input string not in correct format
Console.Write ("The User's IP is: " + userip);
Console.ReadKey ();
}
}
}
以前基本上是
int userip = Convert.ToInt32 (Console.ReadLine());
但我知道 IP 是小数,所以我尝试使用 Double,所以我输入
double userip = Convert.ToDouble (Console.ReadLine());
但现在问题是当我运行 使用"Double" 并输入类似1.1.1.1 的代码时,它显示"Input string was not in a correct format"。但是当我输入一个没有小数的整数时,比如 23 或 2,它起作用了......为什么?
Why?
因为 IP 地址不是 double
。这不是 甚至 一个数字。它是一种数字标签。仅包含一个带有一些数字的点并不能使其成为有效的双精度值(或任何数值)。
喜欢的可以IPAddress.Parse
or IPAddress.TryParse
解析
IP 地址不是十进制格式,请使用 IPAddress.Parse 或 TryParse
IPAddress userIp = IPAddress.Parse(Console.ReadLine);
https://msdn.microsoft.com/en-us/library/1b2h863h(v=vs.110).aspx
尝试使用正则表达式来匹配 IP 地址:
string userIP = Console.ReadLine();
Match match = Regex.Match(userIP, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");
if (match.Success)
{
Console.WriteLine("Valid IP");
}
else
{
Console.WriteLine("Invalid");
}