判断IP

Problem Description
在网络课程上,我学到了很多有关IP的知识。IP全称叫网际协议,有时我们又用IP来指代我们的IP网络地址,现在IPV4下用一个32位无符号整数来表示,一般用点分方式来显示,点将IP地址分成4个部分,每个部分为8位,表示成一个无符号整数(因此不需要用正号出现),如192.168.100.16,是我们非常熟悉的IP地址,一个IP地址串中没有空格出现(因为要表示成一个32数字)。
但是粗心的我,常常将IP地址写错,现在需要你用程序来判断。
 

Input
输入有多个case,每个case有一行,不超过100个字符。
 

Output
对于每个case,判断输入的IP是否正确,如果正确输入YES,否则NO。
 

Sample Input
 
  
192.168.100.16
 

Sample Output
 
  
YES
 

  这个题可以使用sscanf和sprintf来读取和写入IP,然后判断

#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
    char s[20], w[20];
    int a, b, c, d;
    while (gets(s))
    {
        memset(w, 0, sizeof(w));
        sscanf(s, "%d.%d.%d.%d", &a, &b, &c, &d);//用sscanf读取IP
        sprintf(w, "%d.%d.%d.%d", a, b, c, d);//写入标准格式的ip
        if (strcmp(s, w) == 0)//比较
        {
            if ((a >= 0 && a < 256) && (b >= 0 && b < 256) && (c >= 0 && c < 256) && (d >= 0 && d < 256))//ip的数字不能大于256
                cout << "YES" << endl;
            else
                cout << "NO" << endl;
        }
        else
            cout << "NO" << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/loven0326/article/details/79558805