笔试面试记录-字符串转换成整型数等(aatoi,itoa)

时间:2023-03-09 06:33:47
笔试面试记录-字符串转换成整型数等(aatoi,itoa)

  C语言中经常用到字符串与数字之间的相互转换,常见的此类库函数有atof(字符串转换成浮点数)、atoi(字符串转换成整型数)、atol(字符串转换成长整形)、itoa(整型数转换成字符串)、ltoa(长整形转换为字符串)等。

  以下为自定义Myatoi()函数的实现以及测试代码。

 #include <stdio.h>
int Myatoi(char*str){
if (str == NULL){
printf("Invalid Input");
return -;
}
while (*str == ' '){
str++;
}
while ((*str == (char)0xA1) && (*(str + ) == (char)0xA1)){
str += ;
}
int nSign = (*str == '-') ? - : ;//确定符号位
if (*str == '+' || *str == '-'){
str++;
}
int nResult = ;
while (*str >= ''&& *str <= ''){
nResult = nResult * + (*str - '');
str++;
}
return nResult *nSign;
} int main(){
printf("%d\n", Myatoi(""));
return ;
}