I'd highly recommend getting something from
boost to do this for you; but if you've decided to hand-roll it, here's a broken down example of how it can be achieved;
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
typedef char TCHAR;
vector<string> split(TCHAR* str, TCHAR delimiter)
{
const string data(str);
vector<string> elements;
string element;
for(int i = 0; i < data.size(); ++i)
{
if (data[i] == delimiter)
{
elements.push_back(element);
element.clear();
}
else
element += data[i];
}
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; return true;
}
bool validate(TCHAR* ip)
{
const static TCHAR delimiter = '.';
const vector<string> parts = split(ip, delimiter);
if (parts.size() != 4)
return false;
for(int i = 0; i < parts.size(); ++i)
{
int part;
if (!toInt(parts[i], &part))
return false;
if (part < 0 || part > 255)
return false;
}
return true;
}
int main()
{
cout << validate("13.23.12.221") << endl;
return 0;
}
Note that you have to change it to
std::wstring
if you're on a
UNICODE platform, some sort of
#ifdef
should do the trick.
Hope this helps,
Fredrik