1 用atoi函数。
atoi的功能就是将字符串转为整型并返回。其声明为
int atoi(char *str)
比如atoi("1234")会返回整型1234。
2 用sscanf。
sscanf与标准格式化输入函数scanf类似,不过源并非是标准输入,而是字符串。
用sscanf可以处理更复杂的字符串。
比如字符串char * str = "a=1, b=2"
定义int a,b后
可以用
sscanf(str,"a=%d, b=%d",&a,&b)
来将a,b值提取,计算后,a=1, b=2。
字符串转整数可以有两种方法:
1.使用c语言自带的库函数:atoi。
函数原型:int atoi(const char *nptr)
功能:把字符串转成整型数。
例如:
#include <stdlib.h>#include <stdio.h>
int main(void)
{
int n
char *str = "12345"
n = atoi(str)
printf("int=%d\n",n)
return 0
}
/*
输出:
int = 12345
*/
2.可以自己编写一个转换函数:
#include <stdio.h>#include <stdlib.h>
int atoi(char *s)
{
int t=0
while(*s){
t=t*10+*s-'0'
s++
}
return(t)
}
int main ()
{
char a[]="12345"
int n = atoi(a)
printf("n=%d ",n)
return 0
}
/*
输出:
n = 12345
*/
#includevoid main()
{
int a=10
char t[3]
t[0]=a/10+48
t[1]=a%10+48
t[2]='\0'
printf("输出t【3】的值:")
printf("%s\n",t)
}
我指一下你的错误:
1 对字符数组定义的时候出错,出现了反复定义
2 对数字 比如数字a 要把它转换成字符a 必须加上48,将其类型转换
3 要使两者全等 还必须把t[2]赋值为'\0',即为空字符