判断一个IP是否有效(牛客网通过正确)

#include <iostream>
#include <stdio.h>
using namespace std;
bool ValidIpAddr(char const * str)
{
int n, ip1, ip2, ip3, ip4;
char dummy;
bool valid = true;
n = sscanf(str, "%3d.%3d.%3d.%3d%1c", &ip1, &ip2, &ip3, &ip4, &dummy);
if (n != 4 || ((ip1 < 0) || (ip1 > 0xff)) || ((ip2 < 0) || (ip2 > 0xff)) || ((ip3 < 0) || (ip3 > 0xff)) ||((ip4 < 0) || (ip4 > 0xff))) {
valid = false;
}
return valid;
}
int main()
{
string str;
while(cin>>str)
{
if(ValidIpAddr(str.c_str()))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;

}

上一篇:CH579 CH573 CH582 GPIO睡眠唤醒操作


下一篇:cv2.waitKey(10) & 0xFF==27的理解