vendredi 28 avril 2017

Why does this if conditional with string.length() evaluate inconsistently?

int main()
{
    std::string string = "hi";

    std::cout << "Enter index: ";
    int index;
    std::cin >> index;

    if(index < string.length())
        std::cout << index << " is less than " << string.length();
    else
        std::cout << index << " is greater than " << string.length();
}

The string length is 2. When I enter in a negative number, say -3, the if statement evaluates to false and executes else statement & prints -3 is greater than 2. If I enter in a positive number still less than the string length, say 1, if statement evaluates to true & prints 1 is less than 2.

Question:

So while -3 and 1 are both numbers less than string.length(), why is it that only 1 evaluate to true whereas -3 does not in this if statement?

Aucun commentaire:

Enregistrer un commentaire