从string类型的IP转换成四个int

本文介绍了一个简单的C++程序,用于将IPv4地址从点分十进制格式转换为整数表示,并验证输入的有效性。程序通过逐段读取IP地址并检查格式错误,确保输入符合IPv4标准。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
static int count = 0;
int change(string &ipaddress)
{
    int len=ipaddress.length();
    string temp;
    for(int x=0;x<4;x++)
    {
        temp[x]=' ';
    }
    int a=0,f=0;
    for(;count<len;count++)
        {
        if(ipaddress[count] != '.')
        {
            temp[f]=ipaddress[count];
            f++;
        }
        if(ipaddress[count]=='.')
        {
            count++;
            break;
        }   
    }
    a=atoi(temp.c_str());
    return a;
}
bool check(string &str)
{
    int a=0;
    int len=str.length();
    for(int i=0;i<len;i++)
    {
    if((str[i]!='1')&&(str[i]!='2')&&(str[i]!='3')&&(str[i]!='4')&&(str[i]!='5')&&(str[i]!='6')&&(str[i]!='7')&&(str[i]!='8')&&(str[i]!='9')&&(str[i]!='0')&&(str[i]!='.'))
    {
        cout<<"input error"<<endl;
        return false;
        break;
    }
    else
    {
        if(str[i]=='.')
          a++;
    }
 
    }
    if(a==3)
        return true;
    else
    {
        cout<<"input error"<<endl;
        return false;
    }
}
//unsigned int ipad=a*16777216+b*65536+c*256+d;
         
int main()
{
    string ip1,ip2,ip3,dns;
loop1:
    cout<<"please input the first ip:";
    getline(cin,ip1);
    if(check(ip1)==false)
        goto loop1;
loop2:
    cout<<"please input the dns:";
    getline(cin,dns);
    if(check(dns)==false)
      goto loop2;
loop3:
    cout<<"please input the second ip:";
    getline(cin,ip2);
    if(check(ip2)==false)
      goto loop3;
loop4:
    cout<<"please inpit the third ip:";
    getline(cin,ip3);
    if(check(ip3)==false)
      goto loop4;
     
    unsigned int a1=change(ip1);
    unsigned int b1=change(ip1);
    unsigned int c1=change(ip1);
    unsigned int d1=change(ip1);
    count=0;
    unsigned int a2=change(ip2);
    unsigned int b2=change(ip2);
    unsigned int c2=change(ip2);
    unsigned int d2=change(ip2);
    count=0;
    unsigned int a3=change(ip3);
    unsigned int b3=change(ip3);
    unsigned int c3=change(ip3);
    unsigned int d3=change(ip3);
    count=0;
    unsigned int a4=change(dns);
    unsigned int b4=change(dns);
    unsigned int c4=change(dns);
    unsigned int d4=change(dns);
    cout<<a1<<' '<<b1<<' '<<c1<<' '<<d1<<endl;
    cout<<a2<<' '<<b2<<' '<<c2<<' '<<d2<<endl;
    cout<<a3<<' '<<b3<<' '<<c3<<' '<<d3<<endl;
    cout<<a4<<' '<<b4<<' '<<c4<<' '<<d4<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值