![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
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. |
|
|
|
|
|
#2 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
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)? |
|
|
|
|
|
#3 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
if (words [i].size () > max.size ()) max = words [i];
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Wierd compile Error. Need help please. | Keiyentai | Java | 7 | Aug 19th, 2006 1:35 AM |
| hippopotomonstrosesquippedaliophobia | Sane | Coder's Corner Lounge | 25 | Dec 5th, 2005 12:50 PM |
| crack these questions if u can!!! | shagan | C++ | 18 | Apr 3rd, 2005 6:47 AM |
| Find a word in a text file | Dietrich | Python | 29 | Mar 9th, 2005 5:42 PM |
| how to implemen the Find funtion in the text editor to locate a word in a document??? | allen1984us | C++ | 4 | Mar 8th, 2005 10:32 AM |