题解 | 整数与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来分割
全部评论

相关推荐

废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-30 18:19
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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