C++ Notes: Examples: Lefthand words 1

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
// -- lefthand.cpp - Find longest word typed with left hand.
//    Fred Swartz - 2002-09-16

// There may be several words with the longest length.
// This solves the problem by simply printing all words
// which are as long or longer than the current maximum.
// The result is that some shorter words are printed 
// at the beginning, but soon we get to the long words.
// Saving only the longest words is the next program.

#include <iostream>
#include <string>
using namespace std;

//--- prototypes
bool isOnlyLeftHand(string w);

//============================================================= main
int main() {
    string word;     // holds each word as read
    string maxWord = "";  // longest word so far
    int maxlen = 0;  // length of longest word

    while (cin >> word) {
        if (word.length() >= maxlen) {
            if (isOnlyLeftHand(word)) {
                cout << word.length() << " " << word << endl;
                maxlen = word.length();
            }
        }
    }

    return 0;
}//end main


//=================================================== isOnlyLeftHand
bool isOnlyLeftHand(string w) {
    return (w.find_first_not_of("qwertasdfgzxcvb") == string::npos);
}//end isOnlyLeftHand