Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

last character of a string in c++ using n.back() and casting

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();
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading