clupper_stine
clupper_stine

Reputation: 89

C++ stoi: none of the 2 overloads could convert all the argument types

I am coding an exercise relating to string: Input a string (doesn't matter either char[] or C+11 string so I chose the latter) then find the longest (has most characters) ascending substring inside the given string. The idea that I have is scan through the whole string and compare str[i] with str[i+1]. I used stoi to convert each character into int, which looks like this

if (stoi(str[i]) < stoi(str[i+1]))

but it instead gave me error:

error C2665: 'std::stoi': none of the 2 overloads could convert all the argument types

How can I fix it ? Thanks in advance.

Upvotes: 0

Views: 1992

Answers (2)

bipll
bipll

Reputation: 11940

std::stoi converts a string representation of a number into the number itself: stoi("42") should be equal to 42. What you need is a char-to-char comparison which is done as is, without any extra conversions:

std::size_t i{};
while(i < str.size() - 1 && str[i] < str[i + 1]) ++i;

Upvotes: 2

NathanOliver
NathanOliver

Reputation: 180955

stoi is used to convert a std::string to an integer. std::string::operator[] gives you the character at the supplied index, which is not a std::string and therfore cannot be used with stoi.

Since you have a character you can just compare those directly since all character types are integers. So

if (stoi(str[i]) < stoi(str[i+1]))

becomes

if (str[i] < str[i+1])

Upvotes: 1

Related Questions