淡泊明志 宁静致远
分类: C/C++
2006-11-06 08:55:58
题目: 请编写一个 C 函数,该函数将给定的一个字符串转换成整数。
【本程序在Dev C++ 4.9.9.2 下编译通过】
int StrToInt(char * str)
{
int value =
0;
int sign = 1;
if(*str ==
'-')
{
sign = -1;
str++;
}
while(*str)
{
value = value * 10 + *str - '0';
str++;
}
return
sign*value;
}
int main()
{
printf("Number =
%d\n",StrToInt("1234567"));
printf("Number =
%d\n",StrToInt("-1234567"));
printf("Number =
%d\n",StrToInt("2147483647"));
printf("Number =
%d\n",StrToInt("-2147483647"));
system("pause");
return 0;
}
下面的程序考虑了八进制、十进制、十六进制的字符串。
int StrToInt(char * str)
{
int value =
0;
int sign = 1;
int radix;
if(*str ==
'-')
{
sign = -1;
str++;
}
if(*str ==
'0' && (*(str+1) == 'x' || *(str+1) == 'X'))
{
radix = 16;
str += 2;
}
else if(*str == '0')
{
radix = 8;
str++;
}
else
radix = 10;
while(*str)
{
if(radix
== 16)
{
if(*str
>= '0' && *str <= '9')
value = value * radix + *str - '0';
else
value = value * radix + (*str | 0x20)
- 'a' + 10;
}
else
value = value * radix + *str - '0';
str++;
}
return
sign*value;
}
int main()
{
printf("Decimal string
Translation!\n\n");
printf("\"1234567\" =
%d\n",StrToInt("1234567"));
printf("\"-1234567\" =
%d\n",StrToInt("-1234567"));
printf("\"2147483647\" =
%d\n",StrToInt("2147483647"));
printf("\"-2147483647\" =
%d\n",StrToInt("-2147483647"));
printf("\nHex string
Translation!\n\n");
printf("\"0x200\" =
%d\n",StrToInt("0x200"));
printf("\"-0x200\" =
%d\n",StrToInt("-0x200"));
printf("\"0x7FFFFFFF\" =
%d\n",StrToInt("0x7FFFFFFF"));
printf("\"-0x7FFFFFFF\" =
%d\n",StrToInt("-0x7FFFFFFF"));
printf("\nOctal string
Translation!\n\n");
printf("\"0123\" =
%d\n",StrToInt("0123"));
printf("\"-0123\" =
%d\n",StrToInt("-0123"));
system("pause");
return 0;
}