判断输入的字符串是不是iPv4地址。
代码:
#include "stdafx.h"
#include<string>
#include<vector>
#include<iostream>
using namespace std;
bool isipv4(string str)
{
vector<string> vec;
int index = 0;
int start = 0;
index = str.find('.',0);
while (index !=string::npos)
{
string strtemp = str.substr(start,index-start);
if (strtemp!="")
{
for(int j = 0;j< strtemp.length();j++)
{
if (strtemp[j] <'0' || strtemp[j] > '9')
{
return false;
}
}
vec.push_back(strtemp);
start = index + 1;
index = str.find('.',start);
}
else
return false;
}
if (str.substr(start,str.length())!="")
{
vec.push_back(str.substr(start,str.length()));
}
if (vec.size()!=4)
{
return false;
}
for (int i = 0;i < 4;i++)
{
int temp = atoi(vec[i].c_str());
if(temp<0 || temp >255)
return false;
}
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
string str;
cin>>str;
if(isipv4(str))
cout<<"ok";
else
cout<<"no";
return 0;
}