Advertisement
Guest User

Ordered Words Problem C++

a guest
Jul 15th, 2015
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <string>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5.  
  6. bool ordered_word(std::string);
  7.  
  8. int main(int argc, char* argv[]){
  9.   //testing
  10.  
  11.   //std::cout << strcasecmp("A","b") << "\n";
  12.   //std::cout << ordered_word("a")<< "\n";
  13.  
  14.   //stuff the longest words into a vector
  15.   std::vector<std::string> longest;
  16.   int longest_length = 0;
  17.  
  18.   //iterate over stdin
  19.   for (std::string line; std::getline(std::cin,line);) {
  20.     if (ordered_word(line)) {
  21.       //case 1: new word is longer
  22.       //clear previous results and add
  23.       //new result. Also update our
  24.       //longest length.
  25.  
  26.       int new_length = line.length();
  27.       if (new_length > longest_length) {
  28.     longest.clear();
  29.     longest.push_back(line);
  30.     longest_length = line.length();
  31.  
  32.     //case 2: new word is the same length
  33.     //as previous. Add the new result
  34.     //onto the results list.
  35.       } else if (new_length == longest_length) {
  36.     longest.push_back(line);
  37.       }
  38.  
  39.     }
  40.      
  41.   }
  42.  
  43.   //print out the results.
  44.  
  45.   for (int i = 0; i < longest.size(); i ++) {
  46.     std::cout << longest[i] << " ";
  47.   }
  48.  
  49.   std::cout << "\n";
  50.  
  51.  
  52.  
  53. }
  54.  
  55.  
  56. bool ordered_word(std::string word){
  57.   //check for single-character word
  58.   int len = word.length();
  59.   if (len == 1) return true;
  60.  
  61.   //check for empty word (just in case)
  62.   if (len == 0) return false;
  63.  
  64.   std::string first = word.substr(0, 1);
  65.   for (int i = 1; i <= (len - 1); i++){
  66.     std::string second = word.substr(i,1);
  67.     //use c_str to get c equivalen char *
  68.     if (strcasecmp(first.c_str(),second.c_str()) > 0) return false;
  69.     first = second;
  70.   }
  71.   return true;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement