Saturday, April 17, 2010

C++ exercises: Pig-latin


Q: Input a series of words until end of file, converting each one to Pig-latin. If the word begins with a consonant, move the first character of the word to the last position and append "ay". If the word begins with a vowel, simply append "ay". for example,
   Input: this is simple
   Output: histay isay implesay

#include <iostream>
#include <fstream>
#include <string>
                                                                                
using namespace std;
                                                                                
int main(int argc, char *argv[])
{
   if (argc < 2)
   {
      cout << "Usage: " << argv[0] << " <input_file>" << endl;
      return -1;
   }

   fstream f(argv[1]);  // open the input file
   string s;
   string vowel("AEIOUaeiou");
                                                                                
   while (!f.eof())
   {
      f >> s;  // read one word
      if (vowel.find(s[0]) == string::npos)
      {
         // begins with a consonant
         s += s[0];
         s += "ay";
         s.erase(0, 1);
      }
      else
      {
         // begins with a vowel
         s += "ay";
      }

      cout << s << " ";
   }

   return 0;
}

No comments:

 
Get This <