Home > Enterprise >  last character of a string in c using n.back() and casting
last character of a string in c using n.back() and casting

Time:04-13

my input is 12. Why is the output 50?

#include <iostream>
#include <string.h>
using namespace std;

int main() {
   string n;
   cin>>n;
   cout << (int)n.back();
}

CodePudding user response:

my input is 12. Why is the output 50?

Because the value that encodes the code unit '2' in the character encoding that is in use on your system happens to be 50.


If you wish to print the symbol that the code unit represents, then you must not cast to int type, and instead insert a character type:

std::cout << n.back();

If you wish to map a character representing '0'..'9' to the corresponding integer value, you can use character - '0'. Why this works: Regardless of what value is used to represent the digit '0', subtracting its own value from itself will produce the value 0 because z - z == 0. The other digits work because of the fact that all digits are represented by contiguous values starting with '0'. Hence, '1' will be represented by '0' 1 and z 1 - z == 1.

  • Related