I have a small not understanding with increment a char in c. let suppose:
char c = 'A';
now if I do c+1
, the value in c
will be 'B'
. This is fine.
But why when I do the following:
c = c + argv[1][2]
then I got 'r'
in c
why?
please suppose that the argument is "in12345"
, then argv[1][2]
is equal to 1
.
What I am trying to do is for some input, lets say ABCDEF is to receive BDFHJG when I am do it in cyclic manner from the arguments. but I don't understand why the above is not working for me.
why it is not working and what can I do to fix it?
please suppose that the argument is in12345, then argv[1][2] is equal to 1.
No it isn't. It's equal to '1'
, or (assuming ASCII) 49.
'A'
(65) + '3'
(49) = 'r'
(114)
If you want to get the integer 1
from the character '1'
, you need to convert it. A cast won't help; one way to do this is with some arithmetic magic:
char c = 'A';
const int valToAdd = argv[1][2] - '0';
c = c + valToAdd;
// c is now 66, or `'B'`
However, this is a bit of a hack, and it will break if argv[1][2]
is not in the range '0'
to '9'
. You can do further research on the best (better?) ways to get an integer from an ASCII numeric digit.