直接上肝貨吧
#include < iostream>
#include < cstring>
#include < cstdlib>
bool getIp(char *str)
{
char *p = nullptr;
int a[4] = {0};
bzero(a,sizeof(a));
p = strtok(str,"."); //C函數
a[0] = atoi( p);
int i = 1;
while(p = strtok(NULL,"."))
{
a[i] = atoi(p);
i++;
}
if(i != 4)
{
std::cout<<"false"<<std::endl;
return false;
}
for(i = 0;i < 4;++i)
{
if(i == 0&&(a[i] <= 0||a[i] > 255))
{
return false;
}
else if(i > 0&&(a[i] < 0|| a[i] > 255))
{
return false;
}
}
return true;
}
int main()
{
std::cout<<"輸入你想測試的字符串(<40)"<<std::endl;
char str[40] = {0};
bzero(str,sizeof(str));
std::cin.get(str,sizeof(str)).get();
if(getIp(str))
{
std::cout<<"輸入的字符串是一個合法的ip"<<std::endl;
}
else
{
std::cout<<"輸入的字符串不是一個ip"<<std::endl;
}
return 0;
}
測試結果:
官方對這個函數有一段解釋:
感覺沒什麼,只是想記一筆。