题解 | 整数与IP地址间的转换

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    string input1;
    unsigned int input2;
    cin >> input1 >> input2;


    // ip地址转换成10进制
    stringstream ss(input1);
    string token;
    char delimiter = '.';
    vector<int> nums;
    while (getline(ss, token, delimiter)) {
        nums.push_back(stoi(token));
    }
    unsigned int result1 = (nums[0] << 24) + (nums[1] << 16) + (nums[2] << 8) + nums[3];


    // 10进制转换成ip地址
    unsigned int pos1 = input2 >> 24;
    unsigned int pos2 = (input2 >> 16) & 0xff;
    unsigned int pos3 = (input2 >> 8) & 0xff;
    unsigned int pos4 = input2 & 0xff;
    
    ss.clear();
    ss.str("");
    ss << pos1 << "." << pos2 << "." << pos3 << "." << pos4;
    string result2 = ss.str();


    // 输出
    cout << result1 << endl;
    cout << result2 << endl;

    // system("pause");
    return 0;
}
  • 不使用scanf获取输入
  • 使用stringstream来分割
全部评论

相关推荐

哞客37422655...:兄弟别慌!💪 民办本找实习确实难点,但不是没机会。100+简历才2个面试,可能简历需要优化下: 项目经历写具体点,突出测试用例、bug数量等 技能栏把测试工具/方法论写清楚 可以考虑降低预期,先进小厂积累经验 测试岗相对好进,坚持投!现在才半个月,有人投3个月才上岸的😭 加油,offer在路上了🚀
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务