字符串 转 INT?

来源:百度知道 编辑:UC知道 时间:2024/06/04 09:51:57
比如说字符串 'B 5'
怎么得到那个5 的INT值?
我用 I=(INT)s[2]
得出来是i=0...

#include <stdio.h>
char s[10];
int i=(int)s[0];
int main(){
gets(s);
printf("%s\n%d",s,i);
}

/*只打一个5,还是0
5
5
0
*/

你没有对s[]数组进行赋值吧,int i=(int)s[0];
i永远等于0,你没有把字符串加入到数组中

#include <stdio.h>
char s[10];
int i;
int main(){
gets(s);
i=(int)s[2]-48;
printf("%s\n%d",s,i);
}

你下标用错了吧,按你的意思,5是s[1],B是s[0],s[2]是结束字符'\0'

字符直接强制转换(int)‘5’就是ASC码值

char * str="5";
int n=atoi(str);
-------------------
n为字符串str所示数字;