习题7-8 字符串转换成十进制整数 (15分)
代码:
#include <stdio.h>
int main()
{
int sum = 0, sign = 1, flag = 0;
char cha;
cha = getchar();
while (cha != '#') {
if (cha >= '0' && cha <= '9') {
sum = sum * 16 + (cha - '0');
flag = 1;
}
else if (cha >= 'a' && cha <= 'f') {
sum = sum * 16 + (cha - 'a' + 10);
flag = 1;
}
else if (cha >= 'A' && cha <= 'F') {
sum = sum * 16 + (cha - 'A' + 10);
flag = 1;
}
else if (cha == '-' && flag == 0) sign = -1;
cha = getchar();
}
printf("%d", sum * sign);
return 0;
}