用string类实现的提取IP的各个域
之前那个是用字符串指针实现的,发现用string类实现比较简单些#include <iostream>
#include <string>
using namespace std;
bool isDigit(char ch)
{
if((ch-'0')>=0 && (ch-'0')<=9)
return true;
return false;
}
unsigned int strToIP(string str,string &temp)
{
unsigned int result=0;
int value;
int i=0;
while((value=isDigit(str[i])?(str[i]-'0'):-1)>=0)
{
result=result*10+value;
++i;
if(i==str.size())
goto label;
}
label:
if(i!=str.size())
temp=str.substr(i+1,str.size()-i-1);
else
temp="";
return result;
}
void str_to_myip(string str)
{
string temp;
for(int i=0;i<4;++i)
{
unsigned int value=(!str.empty())?strToIP(str,temp):0;
cout<<value<<endl;
str=temp;
}
}
int main()
{
string ip="192.168.1.100";
str_to_myip(ip);
return 0;
}