You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C++实现IPv4地址填充前导零功能

C++ 实现IPv4地址补前导零功能

你给出的原有C版本使用了C风格的字符串操作函数,存在修改原输入串、无合法性校验、缓冲区溢出风险等问题,以下是符合C++编码习惯的实现方案:

C++ 实现代码

#include <string>
#include <sstream>
#include <iomanip>
#include <vector>

std::string padZeroIP(const std::string& ip) {
    std::istringstream iss(ip);
    std::string octet_str;
    std::vector<int> octets;
    
    // 按.分割IP段
    while (std::getline(iss, octet_str, '.')) {
        try {
            int oct = std::stoi(octet_str);
            // 校验每个段的合法范围 0-255
            if (oct < 0 || oct > 255) {
                return "";
            }
            octets.push_back(oct);
        } catch (...) {
            // 转整数失败说明输入非法
            return "";
        }
    }
    
    // 合法IPv4必须是4段
    if (octets.size() != 4) {
        return "";
    }
    
    std::ostringstream oss;
    oss << std::setw(3) << std::setfill('0') << octets[0] << "."
        << std::setw(3) << std::setfill('0') << octets[1] << "."
        << std::setw(3) << std::setfill('0') << octets[2] << "."
        << std::setw(3) << std::setfill('0') << octets[3];
    return oss.str();
}

调用示例

#include <iostream>

int main() {
    std::string ip = "10.0.2.15";
    std::string padded_ip = padZeroIP(ip);
    std::cout << padded_ip << std::endl; // 输出 010.000.002.015
    return 0;
}

方案优势

  • 输入参数为const引用,不会修改原字符串,无副作用
  • 自带IPv4合法性校验,非法输入不会触发崩溃
  • 完全使用C++标准库API,类型安全,不存在缓冲区溢出风险
  • 直接返回std::string对象,无需提前分配字符缓冲区,调用更方便

内容的提问来源于stack exchange,提问作者xinthose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:24:05