Since int atoi(const char* s) takes a pointer to a character field, your last three uses return a number corresponding to consecutive digits starting with & s [pos], for example. it can give 123 for a string of type "123" , starting at position 0. Since the data inside a std::string not required to complete with a zero value, the answer may be something else in some implementation, that is, undefined.
Your βworkingβ approach also uses undefined behavior. It differs from other attempts because it copies the value of s[pos] to another location. It seems to work only until the next byte in memory next to the character c accidentally turns out to be a null or non-digital character, which is not guaranteed. Therefore, follow the recommendations of @aix.
To make it work, you can do the following:
char c[2] = { s[pos], '\0' }; return atoi(c);
source share