1.常见的解决方案
知识点备注: '1' - '0' = 1
具体事例分析:
char str[10] = "12345";
'1' - '0' = 1;
1 * 10 + '2' - '0' = 12;
12 * 10 + '3' - '0' = 123;
123 * 10 + '4' - '0' = 1234;
1234 * 10 + '5' - '0' = 12345;
#include <stdio.h>
#include <string.h>
int main()
{
char str[10] = "123456";
int num = 0;
const char* ptr = str;
while(*ptr)
{
num *= 10;
num += *ptr - '0';
ptr++;
}
printf("num = %d\n",num);
return 0;
}
2.使用atoi函数
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = "1234";
int n = atoi(a);
printf("%d\n",n);
return 0;
}
3.使用sscanf函数
#include <stdio.h>
#include <string.h>
int main()
{
char *a = "1234";
sscanf(a,"%d",&n);
printf("%d\n",n);
return 0;
}