![]() |
Need just a little help
I'm trying to expand my looking for the longest word program. This new version asks the user to input a maximum of 5 words and then outputs the longest word. The program I initially wrote worked great, but what I didn't like about it is that if the user entered 2 words that were the same length, the compiler would just output the first of the two words that were the same length.
So I'm trying to add just a little bit of additional code that will test to see if a word that has been entered is the same length as a word that was previously entered. Only problem is that the code in my if statement is executed all the time, even before the user has had a chance to enter the second word. Maybe I have the if statement in the wrong place. Here is my program: :
int main() |
I think I may know what the problem is. In my code I'm actually comparing the same value of count. So I'm actually comparing the length of the first word with the length of the first word. And since that is always true, the code in the if statement will always run.
Somehow I need to write the code so I'm comparing consecutive values of count like this: :
if (count[0].length == count[1].length)Only snag is I don't quite know how to do that. But I'm working on it. |
I mean:
:
words[0].length == words[1].lengthI think that's what I mean. |
:
words[i].length == words[i+1].lengthNot entirely sure of the variables used, but that's the answer I'd give you |
I tried your suggestion but it doesn't work. Somehow I have to write the if statement or place it in some position that it will test for consecutive values of the counter variable. All my ideas have failed so far.
|
The simplest solution with the knowledge you seem to currently have in C++ would be to keep an array of max's. If the length is equal, append to the array. If the length is greater, start the array over again.
If this doesn't make sense, I can demonstrate. But I don't want to ruin the fun. |
After fully reading the code, I think I know. Switching the order of something seems to work, I hope this is what you're looking for
:
#include <iostream> |
Quote:
This is because you use post increment inside the subscript operator: :
cin >> words[count++];:
if (words[count].length() == words[count].length())edit: peaceofpis code stinks too. lol. |
Oh by the way... my comment explained how to show all the words that have the maximum length, which is how a program should handle this sort of situation. I don't think you should not allow the user to enter same length words. It doesn't make sense why one would need a program that behaves in such a manner.
|
edit 2: peaceofpis code stinks too. lol.
Even though it does what he asked for. Fixed code here: :
doedit: take back my added idea, coding gets sloppier as I go |
| All times are GMT -5. The time now is 2:49 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC