Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   Find the longest word (http://www.programmingforums.org/showthread.php?t=13290)

357mag Jun 6th, 2007 6:10 AM

Find the longest word
 
I've got this other program which I came up with on my own, and I'm not sure if I'm even going about it the right way, cuz I really haven't studied arrays that much yet. The program has three words in an array of strings and uses a loop to find out which word was the longest:

:


int main()
{
        string words[] = {"Bank", "Office", "Mississippi"};
    string max = words[0];
       
        for (int i = 0; i< 3; i++)

                if (words[i] > max)
              max = words[i];

                  cout << "The longest word was " << max;

                  cout << endl;

        return 0;
}


But when I run the program it says the longest word is "Office", when the longest word is really "Mississippi."

So I don't know if there is something wrong with my loop like maybe it's only executing two times and stopping at "Office" or what.

Like I said, I'm not even sure I'm going about this the right way.

357mag Jun 6th, 2007 6:17 AM

Yeah, I think I discovered why the program is reporting that the longest word was "Office". Its comparing character codes. The letter 'O' comes after the letter 'M' and thus has a greater ASCII code.

But is there a way to write the program so it will show which word is the longest(has the most characters in it)?

DaWei Jun 6th, 2007 6:45 AM

if (words [i].size () > max.size ()) max = words [i];


All times are GMT -5. The time now is 2:35 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC