stoi() fails when first letter is an alphabet
I've noticed this just now and it took me a while to realize this trend with stoi(). It intrigues me because there was no mention of this exception on the references that I read. stoi() caused an abort() on my compiler when the first letter of the string is an alphabet.
However it works perfectly as long as the first index is a digit. So "2a" would not have no problem but "a2" would.
Why does this happen and what's an alternative or how to combat this? Are there any other functions that have such drawbacks?
I guess you would have to use a while loop and cut off the first letter of the string if it's isalpha() using <algorithm>
I currently use this:
Code:
try {
taken_answer_int = stoi(taken_answer);
}
catch (...) {
taken_answer_int = -1;
}
Since it doesn't matter if the string doesn't start with a digit for my program, it just assumes that it's an invalid input. (I mean, how do you expect a program to think typing "onehundra2" to be a valid input for how many cookies one wants to have for breakfast..:rolleyes:)
Thanks for reading, Cheers! :biggrin: