Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert single char to int

Tags:

c++

char

int

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*)’

like image 575
Raptrex Avatar asked Nov 26 '09 00:11

Raptrex


People also ask

Can I convert a char to an int?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.


2 Answers

You need to do:

int temp2 = temp - '0';

instead.

like image 97
Gonzalo Avatar answered Sep 22 '22 11:09

Gonzalo


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.

like image 43
Dave S. Avatar answered Sep 21 '22 11:09

Dave S.