题目描述:
现在IPV4下用一个32位无符号整数来表示,一般用点分方式来显示,点将IP地址分成4个部分,每个部分为8位,表示成一个无符号整数(因此不需要用正号出现),如10.137.17.1,是我们非常熟悉的IP地址,一个IP地址串中没有空格出现(因为要表示成一个32数字)。
现在需要你用程序来判断IP是否合法。
示例:
输入1:
10.138.15.1
输出1:
YES
输入2:
127.-2.145.86
输出2:
NO
输入3:
124.257.3.56
输出3:
NO
代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Str;
while (getline(cin, Str))
{
string res = "YES";
int i = 0;
while (i<Str.size())
{
int temp = 0;
if (Str[i] >= '0'&&Str[i] <= '9')
{
temp = Str[i] - '0';
int j = i + 1;
while (j<Str.size() && Str[j] != '.')
{
if ((Str[j] >= '0'&&Str[j] <= '9'))
{
temp = temp * 10 + Str[j] - '0';
}
else
{
res = "NO";
break;
}
j++;
}
i = j+1;
}
else
{
res = "NO";
}
if (res == "NO" || temp>255 || temp<0)
{
res = "NO";
break;
}
}
cout << res << endl;
}
return 0;
}