1

I am curious how this works to produce the provided output. The output is 4 which is the 5th character in the alphabet (which is expected) and subsequent alphabetical characters work all the way to the z character which also returns 25.

Example program

#include <iostream> #include <string> using namespace std; int main() { string str = "e"; int numericalvalue = ((str[0]) - 'a'); //this line of code im trying to understand cout << numericalvalue; return 0; } 
11
  • 8
    Are you familiar with the ASCII table? Commented Aug 29, 2016 at 14:54
  • 1
    characters are internally just numbers (see ASCII table) all you do is subtract the numbers the characters represent. Commented Aug 29, 2016 at 14:54
  • Yes but the decimal value of the character e is 101. Is this subtracting the value of a from it and then just returning it? Commented Aug 29, 2016 at 14:57
  • 1
    There is no need to downvote a legitimate question. The user might be new to programming. Commented Aug 29, 2016 at 14:58
  • 1
    Yes all it does is 101(e) - 97(a) which results in 4 Commented Aug 29, 2016 at 14:59

4 Answers 4

3

It has to do with the ASCII table.

Its character in the set is assigned a unique integer. In your case, the literal 'a' has the value of 97 in the ASCII table and the character e has the value of 101. By subtracting 101 - 97 = 4 you get the final result.

More on the ASCII table can be found here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you yes this is what I asked above. Thank you
2

char is an integral type, so it's implicitly convertible (specifically, it undergoes integral promotion) to type int. Each character that you can represent with a basic char has a numeric value from 0-255 (or -128 to 127). So saying 'a' - '0' is actually valid since it's exactly like saying 97 - 48 with ints.

Comments

1

The character 'a' has the ASCII decimal value 97.

Letters after 'a' have a decimal value greater 97.

The substraction

str[0] - 'a' 

uses the ASCII decimal values which produces the letters position in the alphabet.

Comments

1
char e = 'e'; char a = 'a'; std::cout << "e = " << static_cast<int>(e) << std::endl; std::cout << "a = " << static_cast<int>(a) << std::endl; 

computers don't have such abstract things like "characters". They only work with 1's and 0's.. (numbers). The computer works with a number but knows, once it get's printed out on the screen, use the graphic that's in a .ttf file that represents that "character".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.