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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With