1,strtol()
strtol() 函可将n进制数转换为10进制,用来将字符串转换为长整型数(long),其原型为:long int strtol (const char* str, char** endptr, int base);
error存储第一个转换失败以及以后的的字符串;例如:把11221由二进制转换为十进制:num=strtol(s,&error,2);则num等于3,error='221'。
-
<span style="font-size:14px;"> -
#include<cstdio> -
#include<cstdlib> -
#include<iostream> -
#include<cstring> -
using namespace std; -
int main(){ -
char *error; -
char s[20]; -
while(cin>>s){ -
printf("2 to 10 : %ld\n",strtol(s,&error,2)); -
if(strlen(error)!=0) cout<<"error: "<<error<<endl; -
printf("8 to 10 : %ld\n",strtol(s,&error,8)); -
if(strlen(error)!=0) cout<<"error: "<<error<<endl; -
printf("16 to 10 : %ld\n",strtol(s,&error,16)); -
if(strlen(error)!=0) cout<<"error: "<<error<<endl; -
printf("\n"); -
} -
return 0; -
} </span>
2,十进制数转换为n进制字符串
使用itoa函数,itoa(num,str,n),将num转化为n进制数存到str字符串中,但是itoa并不是一个标准c函数,时window平台特有的函数,
3,sprintf,
sprintf可将整数转化为字符串,sptintf(str,"%d",num)

京公网安备 11010502036488号