0

In my program I have a string of caracters that are all digits and I want to use them as indexes to get values from a vector. But the output of this code is a 15 digit number, so not 1 which is vect[0] i.e. what I thought it would output.

char c = '0';
vector<int> vect = {1};
int i = (int)c;
cout<<vect[i];

I have seen that converting from a caracter to an integer is done with

int i=(int)c;

So i really don't get how that is not an appropriate type for an index.

John Cataldo
  • 105
  • 5
  • 2
    `int i = (int)c` does not results in `i=0`, but int `i=48`. 48 is the position of char '0' in the [ASCII table](http://www.asciitable.com/). You want `int i = (int)c - 48` – Ripi2 Oct 26 '18 at 17:29

1 Answers1

1

First, it is bad practice to use C-style casts (int i = (int) c;), use a static cast instead (int i = static_cast<int>(c);). But indeed, as other mentioned, char are promoted to int automatically.

Then character '0' is not the same as the index 0. Have a look:

int i = c;
std::cout << i << std:endl;

If you want to use the character '0' as index 0, use:

int i = c - '0';
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62