Longest and Shortest String

This is a discussion on Longest and Shortest String within the C++ Programming forums, part of the General Programming Boards category; So, for this exercise I am suppose to take in an input and output the longest and shortest string. This ...

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    110

    Longest and Shortest String

    So, for this exercise I am suppose to take in an input and output the longest and shortest string. This exercise does not seem hard at all but for some reason my code only outputs the longest string, and not the shortest. It just leaves it as blank.

    Example:
    input: a b c d e longesttt ggg
    output: Shortest: a
    Longest: longesttt

    Code:
    #include <iostream>
    #include <string>
    #include <vector>
    #include <conio.h>
    
    using std::cout;
    using std::cin;
    using std::endl;
    using std::vector;
    using std::string;
    
    
    int main(){
        //asks for list of words
        cout << "Please give me a list of words:" << endl;
        
        string x;
        vector<string> words;
        
        //adds the input to the vector
        while (cin >> x){
              words.push_back(x);
              }
        
        //checks to see if user inputted anything
        if (words.size() == 0){
           cout << "I didn't receive any input." << endl;
           
           cout << "Press any key to continue...";
           _getch();
           return 1;
           }
        
        //the containers
        string longest;
        string shortest;
        
        //checks for the shortest and longest string
        for(int i = 0; i != words.size(); i++){
                if(words[i].length() < shortest.length()){
                                     shortest = words[i];
                }
                if(words[i].length() > longest.length()){
                                     longest = words[i];
                }
                
        }
        
        //the output
        cout << "Shortest: " << shortest << endl;
        cout << "Longest: " << longest << endl;
       
        cout << "Press enter to continue...";
        _getch();
        return 0;
    }
    Thank you for your help!!

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Is that, perhaps, because you are getting a string with zero length, and zero length is shorter than a length of 1?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    110
    that actually makes sense...what would be the best way to work with this problem. I was thinking of simply setting shortest as the first of the vector..however this seems more like avoiding the problem rather than solving it.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by dnguyen1022 View Post
    that actually makes sense...what would be the best way to work with this problem. I was thinking of simply setting shortest as the first of the vector..however this seems more like avoiding the problem rather than solving it.
    Ah, actually, that may be the whole problem - your "shortest", before you have set it to something else, is going to be empty. No other string is ever going to be shorter. Set it to the first string before you scan the vector - and if you do the same for the longest, you don't even need to look at the first element of the vector, which saves a tiny bit of string comparison.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Nov 2008
    Posts
    110
    hmm...alright. Thanks!

  6. #6
    Registered User
    Join Date
    Jan 2009
    Posts
    46
    hey dnguyen1022, i was wondering, can u post the final version of ur code? i have to do a similiar exercise, but along with reporting the longest and shortest words in the input, i also have to report the length. thanks

  7. #7
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,243
    Quote Originally Posted by matsp View Post
    Ah, actually, that may be the whole problem - your "shortest", before you have set it to something else, is going to be empty. No other string is ever going to be shorter. Set it to the first string before you scan the vector - and if you do the same for the longest, you don't even need to look at the first element of the vector, which saves a tiny bit of string comparison.
    Or just start with a maximum of -1, because any real string (even a zero-length one) will be longer than that.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  8. #8
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Seems to me you don't really need to store each string, you only need to remember the lengths of the shortest and longest, then compare and update as appropiate.

    This is my first ever C++ program ever!!
    So don't be too hard on me
    How many mistakes did I make?!!
    If it's in single figures I would be impressed!!


    Code:
    #include <iostream>
    #include <string>
    #include <vector>
    #include <conio.h>
    
    using std::cout;
    using std::cin;
    using std::endl;
    using std::vector;
    using std::string;
    
    
    int main(){
        //asks for list of words
        cout << "Please give me a list of words:" << endl;
        
        string x;
        string longest;
        string shortest;
        int count=0;
        int x_len;
    
        while (cin >> x){
              if (count++==0) longest=shortest=x;// could use an else here but it's hardly worth it.
              x_len=x.length();
              if (longest.length() <x_len)  longest=x;
              if (shortest.length() >x_len) shortest=x;
         }
    
        //the output
        cout << "Shortest: " << shortest << endl;
        cout << "Longest: " << longest << endl;
       
        cout << "Press enter to continue...";
        _getch();
        return 0;
    }
    Last edited by esbo; 01-26-2009 at 09:45 PM.

  9. #9
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Ha ha ha it worked, well it did after I added the declaration for x_len which I missed out first time.
    I am a object orientated programmer now

    Could have done this to speed it up!
    Code:
              if (count++==0) { longest=shortest=x; continue; }
    Last edited by esbo; 01-26-2009 at 10:06 PM.

  10. #10
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    435
    Quote Originally Posted by esbo View Post
    Could have done this to speed it up!
    Code:
              if (count++==0) { longest=shortest=x; continue; }
    or you could have used else?

    Code:
    x_len=x.length();
    This is not necessary as it is with strlen() because string.length() has constant time.

    esbo, I give you a pat on the back. You have made a short program and I don't think there is anything (major) to complain about. C++ isn't so bad now is it?
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,754
    Quote Originally Posted by esbo
    This is my first ever C++ program ever!!
    So don't be too hard on me
    That's okay, you even fixed dnguyen1022's weird returning of 1 when main completes successfully.

    However, I note that you have a good idea:
    Quote Originally Posted by esbo
    Seems to me you don't really need to store each string, you only need to remember the lengths of the shortest and longest, then compare and update as appropiate.
    But you did not actually implement it. Instead of just storing the lengths of the shortest and longest strings, you stored the shortest and longest strings themselves. Nonetheless, maybe we should leave this for dnguyen1022 to do.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,261
    Code:
    copy(issi(cin), issi(), bi(data));
    sort(data.begin(), data.end(), [](const string & l, const string & r) {l.length() < r.length()});
    copy(data.begin(), data.end(), ossi(cout, "\n"));
    ^_^

    Soma

  13. #13
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by NeonBlack View Post
    or you could have used else?

    Code:
    x_len=x.length();
    This is not necessary as it is with strlen() because string.length() has constant time.

    esbo, I give you a pat on the back. You have made a short program and I don't think there is anything (major) to complain about. C++ isn't so bad now is it?
    Well I suppose not, but basically I had a program to copy which always makes things easier.
    If I tried that again from scatch I am sure I would have had loads of trouble as I have a whole lot of new syntax to learn, so it's is usually 'not worth the bother' as I could do it in C anyway. Yes it has some stuff which make things easier like not having to specify the format in cout.

  14. #14
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Well encouraged by my 'success' I tried to convert one of my pretty big C programs to C++
    I had to rearrange the function order and stick a few voids in, but I got it to compile, however
    it didn't get very far before it fell over.
    Will have to have a look at it.

    Actually it does do most of it, falls over at the end when it prints it's output so it is probably nothing major
    so I should be able to sort it out.

    Actually it did find a bug in my program which I was not aware of, I was adding a float to an int which
    the C compiler never complained about and it would, I think, have affected my results slightly.

    So maybe C++ is not that bad after all

    If (when) I do get it running I will do a comparison of runtimes for the C and C++ versions, however
    I expect as it is all C anyway, there won't be any different?
    Last edited by esbo; 01-26-2009 at 11:45 PM.

  15. #15
    Registered User
    Join Date
    Jan 2007
    Posts
    330
    you could also just remember the indexes of the shortest and longest string and in the print. No copying of strings then.

    Code:
    int shortest = 0, longest = 0;
    
    for (int i = 1; i < words.size(); i++)
    {
      const string &word = words[i];
    
      if (word.length() < words[shortest])
        shortest = i;
      if (word.length() > words[longest])
        longest = i;
    }
    
    cout << words[shortest] << endl;
    cout << words[longest] << endl;

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. text processing assignment
    By nellosmomishot in forum C Programming
    Replies: 28
    Last Post: 11-25-2008, 02:56 PM
  2. working on a string tough string prog, need help
    By Brokn in forum C Programming
    Replies: 1
    Last Post: 11-13-2005, 03:14 PM
  3. using strlen and finding shortest and longest words
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 09-30-2001, 06:09 PM
  4. length of string etc.
    By Peachy in forum C Programming
    Replies: 5
    Last Post: 09-27-2001, 12:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21