Convert single char to int

2019-03-26 14:44发布

How can I convert char a[0] into int b[0] where b is a empty dynamically allocated int array

I have tried

char a[] = "4x^0";
int *b;
b = new int[10];
char temp = a[0]; 
int temp2 = temp - 0;
b[0] = temp2;

I want 4 but it gives me ascii value 52

Also doing

a[0] = atoi(temp);

gives me error: invalid conversion from ‘char’ to ‘const char*’ initializing argument 1 of ‘int atoi(const char*)’

标签: c++ char int
3条回答
在下西门庆
2楼-- · 2019-03-26 14:52

You can replace the whole sequence:

char a[] = "4x^0";
int *b;
b = new int[10];
char temp = a[0]; 
int temp2 = temp - 0;
b[0] = temp2;

with the simpler:

char a[] = "4x^0";
int b = new int[10];
b[0] = a[0] - '0';

No need at all to mess about with temporary variables. The reason you need to use '0' instead of 0 is because the former is the character '0' which has a value of 48, rather than the value 0.

查看更多
欢心
3楼-- · 2019-03-26 15:06

You need to do:

int temp2 = temp - '0';

instead.

查看更多
Deceive 欺骗
4楼-- · 2019-03-26 15:07

The atoi() version isn't working because atoi() operates on strings, not individual characters. So this would work:

char a[] = "4";
b[0] = atoi(a);

Note that you may be tempted to do: atoi(&temp) but this would not work, as &temp doesn't point to a null-terminated string.

查看更多
登录 后发表回答