Question about unsigned chars

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
std::map<uchar, int> m = {
   std::make_pair('1', 346),
   std::make_pair('2', 345),
   std::make_pair('3', 436)
};

int main()
{
    int i = 2;
    uchar u = static_cast<uchar>(i); 
    int value = m[u];
    std::cout << value;
} 


Why this doesn't print '345'? If i set the value of 'u' to '2' it works fine.
Last edited on
This would suffice:
std::map<uchar, int> m = { { '1', 346 }, { '2', 345 }, { '3', 436 } } ;


> Why this doesn't print '345'? If i set the value of 'u' to '2' it works fine.

1
2
int i = 2 ; // value of i is the integer 2
int j = '2' ; // value of j is the code-point for the character '2' 

The value of j would be 50 if the the character encoding is ASCII http://en.wikipedia.org/wiki/ASCII
242 if the character encoding is EBCDIC http://en.wikipedia.org/wiki/EBCDIC etc.
Well, that's pretty much the same, isn't it? My question is how to convert 2 to '2'. Also, that integer in the example is not necessary at all, sorry. Here's my updated code.

1
2
3
4
5
6
7
8
9
10
11
12
std::map<uchar, int> m = {
    { '1', 346 },
    { '2', 345 },
    { '3', 436 }
};

int main()
{
    uchar u = 2; 
    int value = m[u];
    std::cout << value;
} 
Last edited on
This is guaranteed: '0' + 1 == '1', '0' + 2 == '2' etc. up to '0' + 9 == '9'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::map<uchar, int> m = {
    { '1', 346 },
    { '2', 345 },
    { '3', 436 }
};

int main()
{
    uchar u = 2; 
    if( u > 0 && u < 4 )
    { 
         int value = m[ u + '0' ];
         std::cout << value;
    }
} 
Last edited on
Yeah, that works fine. Thank you.
Topic archived. No new replies allowed.