Reputation: 21
I have been doing some string problems. The problem now is to check if a ip is valid or not. for example 255.6.13.4. The ip is stored in a string.Now i have to check whether the numbers lie between 0 to 255. Is there any way to split the ip and compare with numbers or any other way around it. thanks in advance
Upvotes: 1
Views: 35
Reputation: 23832
Use stringstreams
and std::getline()
, it has a delimiter parameter.
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
std::string str = "123.231.0.43";
std::stringstream test(str);
std::string temp;
int temp_int;
std::vector<int> addr_elements; //int vector, you can use a string vector if you prefer
while (std::getline(test, temp, '.')) //split by delimiter '.'
{
std::stringstream ssint(temp);
ssint >> temp_int; //string to int
addr_elements.push_back(temp_int); //now you have a vector of integers
}
for(int i : addr_elements){ //test print the vector
std::cout << i << " ";
}
}
Upvotes: 1