0

What I'm trying to do: I have an array of characters, something that looks like "vm1". I would like to set an integer variable equal to the value of the last element of the array, in this case 1. I don't need anything fancy, as the length of the array in my case will always be 3.

My code:

char *string = "vm1";
int number = (int)string[2];

printf("Character from string: %c", string[2]);
printf("Number: %d", number);

Output:

Character from string: 1
Number: 55

What is going wrong: For some reason, the number is always some incorrect value. 55 was just from this case. Another method I tried was using sscanf but it produces similar results.

1 Answers1

0

You have to convert the ASCII value of the character to the actual decimal number. To do so you have to use:

int number = string[2];
number = number - '0';

Why is that? If you search for an ASCII table you will find that the character '1' corresponds to a decimal value of 49, so if you subtract the ASCII value of '0' (48) you get the right decimal result, 1.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
alenada99
  • 356
  • 1
  • 6