通俗易懂兄弟们
最短ip : 1.1.1.1 长度为7
最长ip: 255.255.255.255 长度为15
然后就是判断每个点之前的temp字符串是否为合法的1-255数字,很简单。
记得ip不能以0开头,022是非法的
#include <iostream>
#include<string>
using namespace std;
int toInt(string a) {
int len = a.size();
int res = 0;
for (int i = 0; i < len; i++) {
res = res * 10 + int(a[i] - 48);
}
return res;
}
bool isIP(string & str) {
bool flag = true;
int len = str.size();
// 检查ip长度,最短7位,最长15位
if (len < 7 or len > 15) {
return false;
}
//对输入字符串的首末字符判断,若是.则false
if (str[0] == '.' || str[len - 1] == '.') return false;
string temp = ""; // 存放临时的字符串
for (int i = 0; i < len; i++) {
if (str[i] != '.') {
temp += str[i];
continue;
}else {
// 第一个是0 , 非法
if (temp[0] == '0') return false;
for (int j = 0; j < temp.size(); ++j) {
if (isdigit(temp[j])) { // 临时变量temp的每一个字符判断是否为数字
continue;
}
else {
return false;
}
}
// 全是数字 ,看是否小于255
int a = toInt(temp);
if (a >= 1 and a <= 255) {
temp = "";
continue;
}
else {
return false;
}
}
}
// 还有最后一个 点后面的 ,需要判断
// 第一个是0 , 非法
if (temp[0] == '0') return false;
for (int j = 0; j < temp.size(); j++) {
if (isdigit(temp[j])) {
continue;
}
else {
return false;
}
}
// 全是数字 ,看是否小于255
int a = toInt(temp);
if (a >= 1 and a <= 255) {
temp = "";
}
else {
return false;
}
return true;
}
int main()
{
string ip;
while (cin >> ip) {
if (isIP(ip)) {
cout << "That's true IP ! " << endl;
}
else if (ip == "stop") {
return 0;
}
else {
cout << "Sorry , it's wrong IP" << endl;
}
}
}
测试用例
♥根据长度,字符是否合法进行设计用例吧
测试用例
-
正确的IP:192.168.1.101
-
输入为空: null
-
边界值:
小于7:17.17
等于7:1.1.1.1
长度为8的ip地址: 11.1.1.1长度小于15
长度等于15
长度大于15 -
首尾不能以.作为开头或结尾
-
我们都知道ip地址固定有4个".",并且按".“分割之后每隔分割的字符,不能以’0’开头,且按”."分割之后必须在0-255
…
请看到的兄弟测试一下我的程序有无漏洞,你随便输入ip看返回是否正确。如果你发现到一个反例,请务必在评论区或私信给我,谢谢!