-1

I'm trying to figure out a code that a friend sent me and I couldn't figure out why this certain code exists.

The goal is that when you type a 3 digit number sequence in string, it converts it to int and prints the sequence in reverse.

string s;
cout <<"enter integer sequence";
cin >> s;
int firstdig, seconddig, thirddig;
firstdig = s[0];
seconddig = s[1];
thirddig = s[2];

cout << thirddig << seconddig << firstdig;

Here is the problem with this code

When I input "123", the output becomes "515049" instead of "321"

However

This is the code that apparently fixes the problem

string s;
cout <<"enter integer sequence";
cin >> s;
int firstdig, seconddig, thirddig;
firstdig = s[0] - '0';
seconddig = s[1] - '0';
thirddig = s[2] - '0';

cout << thirddig << seconddig << firstdig;

This time, I input "123", the output becomes "321"

My main question is, where did "515049" come from, and what does the code "- '0'" do? I don't know what that code does. C++ C++ C++

limbostack
  • 13
  • 2
  • 2
    51, 50 and 49 are the ASCII values of '3', '2' and '1' respectively. It follows that the ASCII value of '0' is 48, and that explains your second observation. – Paul Sanders Sep 24 '20 at 23:21
  • The digit varlables should be `char`, not `int`. – Barmar Sep 24 '20 at 23:28

1 Answers1

1

In the first code, you are converting a char into an int directly which, as it has been pointed out in the comments, gets the ASCII value of the characters.

In the second code, when you substract the ASCII value of the characters and '0' you get the original value of the character.

kalia
  • 219
  • 1
  • 13