Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Why is my comparison between int and str.length() not working?

I am sending an array of names to a function that should compute length of each name and send back the largest one as number of characters. My comparison between longest and names[i].length() is never true. I initialize longest to -1 so first name should replace -1 with the length of characters in that name, however at the end of the function it return longest with my initial value of -1

#include <iostream>
#include <string>
using namespace std;

int findLongestName(string names[], int numNames);

int main() {
   string names[25] {"Bob Hope", "Steve Nice", "Mary Jane", "James Higgenbothem", "Ace Blue"};
   int numNames = 5;
   int longName;

   longName = findLongestName(names, numNames);
   cout << "Longest name is " << longName << " characters.\n";

   system("PAUSE");
   return 0;
}

int findLongestName(string names[], int numNames) {
    int longest = -1;

    for (int i = 0; i < numNames; i++) {
        if (names[i].length() > longest) {
            longest = names[i].length();
        }
    }

    return longest;
}

Can someone take a look and explain what I am doing wrong? I should/want to receive 18 back from the function for name James Higgenbothem.

like image 667
William S Avatar asked Mar 29 '20 07:03

William S


1 Answers

The issue is with the data type names[i].length() returns an unsigned int. Comparing -1 with names[i].length() will always give you a false.

int findLongestName(string names[], int numNames) {
    unsigned int longest = 0;

    for (int i = 0; i < numNames; i++) {
        if (names[i].length() > longest) {
            longest = names[i].length();
        }
    }

    return longest;
}
like image 118
albusSimba Avatar answered Oct 15 '22 07:10

albusSimba