некоторые мелкие исправления для исправления некоторых случаев, например 127..0.1, 127.0.0 .. и удаления пробелов, если есть:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <stdio.h>
using namespace std;
vector split(char* str, char delimiter)
{
const string data(str);
vector elements;
string element;
for(int i = 0; i 0) {//resolve problem: 127.0..1
elements.push_back(element);
element.clear();
}
}
else if (data[i] != ' ')
{
element += data[i];
}
}
if (element.length() > 0)//resolve problem: 127.0..1
elements.push_back(element);
return elements;
}
bool toInt(const string& str, int* result)
{
if (str.find_first_not_of("0123456789") != string::npos)
return false;
stringstream stream(str);
stream >> *result; // Should probably check the return value here
return true;
}
/** ipResult: the good ip address, e.g. spaces are removed */
bool validate(char* ip, string *ipResult)
{
const static char delimiter = '.';
const vector parts = split(ip, delimiter);
*ipResult = "";
if (parts.size() != 4)
return NULL;
for(int i = 0; i 255)
return NULL;
if (i == 3) {
*ipResult += parts[i];
} else {
*ipResult += (parts[i] +".");
}
}
return true;
}
int main()
{
string ip;
printf("right %d\n", validate("127.0.0.1", &ip));
printf("good ip: %s\n", ip.c_str());
printf("wrong %d\n", validate("127.0.0.-1", &ip));
printf("good ip: %s\n", ip.c_str());
printf("wrong %d\n", validate("127..0.1", &ip));
printf("good ip: %s\n", ip.c_str());
printf("wrong %d\n", validate("...0.1", &ip));
printf("good ip: %s\n", ip.c_str());
printf("wrong %d\n", validate("127.0.0.", &ip));
printf("good ip: %s\n", ip.c_str());
printf("right %d\n", validate("192.168.170.99", &ip));
printf("good ip: %s\n", ip.c_str());
printf("right %d\n", validate("127.0 .0 .1", &ip));
printf("good ip: %s\n", ip.c_str());
printf("\n");
system("pause");
return 0;
}