这里我有一个char类型变量,它保存一个数字值作为字符串说21,我想将21分配给一个整数变量。我做了以下的事情,但它打印-12.why它是打印-12和我怎么样我的int变量可以得到21?
#include<stdio.h>
int main(){
char character = "21";
int x = (int)character - '0';
printf("%d",x);
}
答案 0 :(得分:3)
使用“sscanf”。
int main(){
char *character = "21";
int x = 0;
sscanf(character, "%d", &x);
printf("%d",x);
}
答案 1 :(得分:0)
从字符串转换为整数的正确方法是使用atoi()
或sscanf()
函数。