贵州大学2017机试——IP地址(C++)

IP地址

Time Limit: 1000 ms
Memory Limit: 256 mb

输入一串字符,判断该字符串是否为点分十进制的IP地址,若是则转换为16进制输出,否则输出“Error”

例如

输入:192.41.6.20

输出:0xC0290614

输入:257.32.23.1

输出:Error

 输入输出格式

输入描述:

按题意输入。
注意:输入可能是任意的一个字符串,比如“abc.bas.fefe.4r4”或者“23.23.11.23.123”
这都是不合法的IP地址

输出描述:

按题意输出。

 输入样例#:

192.41.6.20

 输出样例#:

0xC0290614
#include<iostream>
#include<string.h>
using namespace std;
//转化16进制
void hex(int x, char *ans){
	int i = 0;
	do{
		int temp = x % 16;
		if(temp < 10) ans[i++] = temp + '0';
		else{
			char temp_char = 'A' + (temp-10);
			ans[i++] = temp_char;
		}
		x = x / 16;
	}while(x > 0);
}
int main(){
	char str[105];
	while(cin>>str){
		int len = strlen(str);
		int count = 0,num[5];
		memset(num,0,sizeof(num));
		bool ch_flag = true,flag = true;
		for(int i = 0; i < len; i++){
			if(str[i] == '.'){
				count++;//count记录'.'的个数
				ch_flag = false;
			}
            //长度不符合标准或包含非法字符
			if((count>3)||((str[i]!='.')&&((str[i]<'0')||(str[i]>'9')))){
				cout<<"Error"<<endl;
				flag = false;
				break;
			}
            //当前字符不为 '.'时进行计算
			if(ch_flag){
                //将每部分对应的字符串转化为数字存入num数组
				num[count] = num[count]*10 + (str[i]-'0');
				if(num[count] > 255){
					cout<<"Error"<<endl;
					flag = false;
					break;
				}
			}
			else ch_flag = true;
		}
        //格式正确时进行转化结果输出
		if(flag){
			cout<<"0x";
			for(int i = 0; i < 4; i++){
				char ans[10];
				memset(ans,0,sizeof(ans));
				hex(num[i],ans);
				int len_ans = strlen(ans);
				for(int i = 0; i < 2-len_ans;i++) cout<<'0';
				for(int i = len_ans-1; i >= 0; i--){
					cout<<ans[i];
				}
			}
			cout<<endl;
		}
	}
	return 0;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值