C语言---字符转数字
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
#include <stdio.h>
#include <string.h>
int str2int(const char *str)
{
int temp = 0;
const char *ptr = str;
if (*str == '-' || *str == '+')
{
str++;
}
while(*str != 0)
{
if ((*str < '0') || (*str > '9'))
{
break;
}
temp = temp * 10 + (*str - '0');
str++;
}
if (*ptr == '-')
{
temp = -temp;
}
return temp;
}
int main(void) {
printf("Hello World\n");
char buf[4] = "123";
const char *ptr = "3021";
int num = 0;
for (int i = 0; i < strlen(buf); i++)
{
num = num * 10 + buf[i] - '0'; // 通过减去'0'可以将字符转换为int类型的数值
}
printf("%d\n",num);
num = str2int(ptr);
printf("%d\n",num);
return 0;
}