About converting string to integer | Sololearn: Learn to code for FREE!

+8

About converting string to integer

So, here is a piece of code in C++ int something = string.at (string.length () - 1) - '0'; Can anyone explain me how this works? Thanks in advance

3/16/2017 3:58:34 PM

Suzie

4 Answers

New Answer

+9

Ha ha Where did you find this stuff from,huh? It was cools! Explain: string a = "JavaScript"; //I like javascript! int something = a.at(a.length() - 1) - '0'; cout << something << endl; //Result will be 68 because of you assign the value of "something" into "int". this will return the number of character of that string Ah...How to explain this? number of 't' is 116 (from a.length() - 1) number of '0' is 48 minus together will be 68! And that isn't converting :/ Maybe you don't understand.I'm srry I'm not good at explaination!

+1

If you are still looking for an answer it is used to convert the numeric characters like '0' '1' '9' etc to integers 0 1 9 and so on. ASCII value of '0' is 48 and if you subtract this value from ascii value of 9 which is 57 you get 57-48=9. So what it basically does is takes a character from '0'-'9' and converts it to integer from 0-9. It isn't useful for alphabets.

0

http://www.cplusplus.com/reference/string/string/at/ string.at (string.length ()-1) returns the last character of the string. -1 because the method at returns the character at a given position starting at 0. string myName = "Steve"; string c = myName.at (2); c will contain "e" then you put the result of the at function in an int. but the result is a char& , so why put it in an integer. I am not even sure if it works

0

pjazzs××[email protected] 😆😉😉🍜🍜🍖🥓🍖🌮🌮🥙🌮🍘🍘🍘🍤😉😉😆😆😇😆😉🙂😇😉😇😉😆😆🍥🍰🍥🍡🍺🥂