0
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?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
lostsoul
  • 61
  • 6
  • 2
    Possible duplicate of [Implicit type conversion rules in C++ operators](http://stackoverflow.com/questions/5563000/implicit-type-conversion-rules-in-c-operators) – Michael Albers Apr 29 '17 at 03:01
  • 1
    `string.length()` is unsigned so the other operands will be promoted to `unsigned` as well. `-3` converted to an `unsigned` value is a very large number. – Michael Burr Apr 29 '17 at 03:01
  • Don't spam tags! C and C++ are different languages. – too honest for this site Apr 29 '17 at 03:08
  • return type of `string.length()` is `string::size_type`. `string::size_type` is `Alloc::size_type`. (`Alloc` is `allocator`) `Alloc::size_type` is `size_t`. `size_t` is unsigned integer type. – BLUEPIXY Apr 29 '17 at 03:11

2 Answers2

3

When you compare an int with an unsigned int, the int converts to unsigned int. So if it was a negative value before, it becomes a very big positive integer. That is why it becomes larger than the size of the string.

Try doing this:

 unsigned int x = 100;
 int y = -1;

 std::cout << (x < y? "Yes" : "No" << std::endl; //prints Yes

 std::cout << static_cast<unsigned int>(y) << std::endl; //prints big +ve number

Note that the std::string::size() and std::string::length() both returns std::string::size_type which is just an alias of some unsigned integral type, could be unsigned int, unsigned long, or size_t(which is usually an alias again of some unsigned integral type).

Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

try this

because .length or .size is an unsigned int, the regular int is automatically converted. Store it in a variable of int data type and this should solve your problem.

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

    std::cout << "Enter index: ";
    int index;
    int length = string.size();
    std::cin >> index;

    if(index < length)
        std::cout << index << " is less than " << string.length();
    else
        std::cout << index << " is greater than " << string.length();
}
Paul Isaac
  • 84
  • 9
  • thank you for your response. it indeed did work. Just couldn't wrap my head around why that would work, but now I see why. – lostsoul Apr 29 '17 at 03:26