how to convert char array to integer in C?

2019-04-14 22:04发布

How can I convert the char array x to an integer 89 in the code below? Thank you

int main(int argc,char *argv[]){
    char y[13] = "0123456789012";
    char x[3];
    int integer_value;

    x[0] = y[8];
    x[1] = y[9];
    x[3] = '\0';

    integer_value=atoi(x);
}

1条回答
甜甜的少女心
2楼-- · 2019-04-14 22:42

You're done; atoi() is one way of doing the conversion from a string to an integer. You could also use strtol() or sscanf().

UPDATE: Assuming, of course, that you fix the termination, i.e. set x[2] = '\0'; rather than x[3].

查看更多
登录 后发表回答