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;
}