char to int

I need convert char (dont char[]) specifically '1', '2' or '3' to 1, 2 or 3.
I make this:
1
2
3
4
char a = '1';
string b;
b += a;
string c = atoi(b.c_str());
I think this dont optimum, yeah?
If it's working, then it's OK. Another way to do it is using stringstreams:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <sstream>

using namespace std;

int main()
{
    stringstream str;
    
    str << "1";

    double x;
    str >> x;
}


The conversion you did is C, what I offered you is C++. The advantage here is that you don't have to care what type x has. As long as the operator>> for x is defined and implemented (and it's for all native types), you can do the conversion with no problems.
Thank
Alternatively, for digits, you can use the ASCII codes. A char is actually just a number interpreted through the ASCII table. By looking at the table, you can find that '0' is 48, '1' 49 and so on until '9' as 57. As a result, you can do this:

1
2
char a = '6';
int b = a-48;

b now holds 6 (the value), while a holds '6' (the character).
Last edited on
Thank, this even easier.
Last edited on
Alternatively too, for example:


1
2
3
4
5
6
7
8
9
10
#include <iostream>

using namespace std;

int main()
{
    char a = '6';
    int b = a-'0';
    cout <<b;
}


It is logic: '0' is 48 :)
Topic archived. No new replies allowed.