C++``判断输入IP地址的规范性
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
bool isIP4(string s)
{
const char *ip = s.data(); //string类型转换为char类型
int count=0;
char ip1[15];
cout << ip << endl;
cout << strlen(ip) << endl; //计算字符串的长度
//cout << strlen(IP) << endl;
int IP_Len = strlen(ip);
for (int i = 0; i < IP_Len; i++)
{
if (isdigit(ip[i]) == 0 && ip[i] != '.') //判断字符串是否为数字
{
cout << ip[i] << endl;
return false;
}
if (ip[i] == '.') //判断‘.’的个数
{
count++;
}
if (i<= IP_Len -1) //同时出现两个..返回错误。
{
if (ip[i] == ip[i + 1] && ip[i + 1]=='.')
{
cout << "同时出现两个:." << endl;
return false;
}
}
}
if (count != 3)//如果‘.’的个数不等于3,判定IP不规范
{
cout << count << endl;
return false;
}
//以.分割字符串,判定字符串的数值是否大于255,或小于0;
//获取第一个字符串
strcpy_s(ip1, s.c_str());
char *p[5];
char *buf;
p[0] = strtok_s(ip1, ".", &buf);
int i = 0;
while (p[i])
{
i++;
p[i] = strtok_s(NULL, ".", &buf);
}
for (int i = 0; i < 4; i++)
{
if (atoi(p[i])<0 || atoi(p[i])>255)
{
cout << "数值大于255,或小于0" << endl;
return false;
}
}
return true;
}
int main()
{
string IP = "192.254.1.100";
if (isIP4(IP))
{
cout << "true" << endl;
}else
cout << "false" << endl;
system("pause");
return 0;
}