学习要点
- bitset<8>
- ostringstream
- stoi
- string.find
- string.substr
题目链接
题目描述

解法
cpp
#include <iostream>
#include <bits/stdc++.h>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
int A = 0;int B = 0;int C = 0;int D = 0;int E = 0;int W = 0;int P = 0;
string line_str;
while (getline(cin, line_str)) {
string ip; string str1; string str2; string str3; string str4;
string net;
ip = line_str.substr(0, line_str.find('~'));
net = line_str.substr(line_str.find('~') + 1);
// 先检查ip
int point1 = ip.find('.');
int point2 = ip.find('.',point1+1);
int point3 = ip.find('.',point2+1);
if((point1 == 0) || ( point1+1 == point2) || (point2+1 == point3) || (point3 == ip.size() -1))
{ // 检查ip是否合法
W++;
continue;
}
str1 = ip.substr(0,point1);
str2 = ip.substr(point1+1,point2-point1-1);
if(str1 == "0" || str1 == "127")
{ // 检查是否是特殊地址
continue;
}
// 再检查子网掩码
int point_1 = net.find('.');
int point_2 = net.find('.',point_1+1);
int point_3 = net.find('.',point_2+1);
if((point_1 == 0) || ( point_1+1 == point_2) || (point_2+1 == point_3) || (point_3 == net.size() -1))
{ // 检查子网掩码是否合法---点号
W++;
continue;
}
int num1 = stoi(net.substr(0,point_1));
int num2 = stoi(net.substr(point_1+1,point_2 - point_1 - 1));
int num3 = stoi(net.substr(point_2+1,point_3 - point_2 - 1));
int num4 = stoi(net.substr(point_3+1));
ostringstream outstr;
bitset<8> binary1(num1); bitset<8> binary2(num2); bitset<8> binary3(num3); bitset<8> binary4(num4);
outstr << binary1 << binary2 << binary3 << binary4;
string binary_net = outstr.str();
int zero_pos = binary_net.find('0');
if(zero_pos == string::npos || binary_net.find('1') == string::npos )
{ // 检查子网掩码是否合法---全为0或全为1
W++;
continue;
}
bool flag = false;
for(int i = zero_pos+1; i<binary_net.size();i++)
{
if(binary_net[i] == '1')
{
flag = true;
}
}
if(flag)
{ // 检查子网掩码是否合法---连续1后连续0
W++;
continue;
}
// 至此全部合法且不为特殊地址
if(str1 == "10" || (str1 == "172" && stoi(str2) >= 16 && stoi(str2)<= 31) || (str1 == "192" && str2 == "168"))
{
P++;
}
if(stoi(str1) >= 1 && stoi(str1) <= 127)
{
A++;continue;
}
if(stoi(str1) >= 128 && stoi(str1) <= 191)
{
B++;continue;
}
if(stoi(str1) >= 192 && stoi(str1) <= 223)
{
C++;continue;
}
if(stoi(str1) >= 224 && stoi(str1) <= 239)
{
D++;continue;
}
if(stoi(str1) >= 240 && stoi(str1) <= 255)
{
E++;continue;
}
}
cout << A << ' ' << B << ' ' << C << ' ' << D << ' ' << E << ' ' << W << ' ' << P << endl;
}