Write a function htoi(s),which converts s string of hexadecimal digits(including an optional 0x or 0X) into its equivalent of interger value. The allowable digits are 0 through 9, a through f, and A through F.
#include<stdio.h>
#define YES 1
#define NO 0
main(char s[])
{
int i,n,INDEX,hexa;
i = 0;
if(s[i] == '\0')
{
++i;
if(s[i] == 'x'||s[i] == 'X')
++ i;
}
n = 0;
INDEX = YES;
for(;INDEX == YES;++i)
{
if(s[i] >= '0' && s[i] <= '9')
hexa = s[i] - '0';
else if(s[i] >= 'a' && s[i] <= 'f')
hexa = s[i] - 'a' + 10;
else if(s[i] >= 'A' && s[i] <= 'F')
hexa = s[i] - 'A' +10;
else
INDEX = NO;
if(INDEX == YES)
n = 16*n + hexa;
}
return n;
}
……………………………………………………………………………………………………………………hcoi.c运行结果:
segmentation fault
关于segmentation fault,暂不提。这个题目的错误也可以解决。