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 41 42 43 44 45 46 47 48 49
|
#include <iostream>
#include <string>
using namespace std;
// takes a string argument and returns the pigLatin equivalent
string pigLatin(string);
int main()
{
string mySentence;
getline(cin, mySentence);
mySentence = pigLatin(mySentence);
cout << mySentence << endl;
return 0;
}
string pigLatin(string word){
//pigLatWord holds word translated in pig latin.
//pigLatSentence holds entire translated sentence.
string pigLatWord, pigLatSentence = "";
int length = 0, index = 0;
while (word[index] != '\0'){
// .find returns -1 if no match is found
if (word.find(' ', index) != -1){
length = word.find(' ', index);
length -= index;//length - index = the number of characters in a word
pigLatWord = word.substr(index, length);
pigLatWord.insert(length, " ");
pigLatWord.insert(length, 1, word[index]);//first letter is inserted at the end of the string
pigLatWord.erase(0, 1);// erase first letter in string
index += length + 1;//adding one moves index from 'space' to first letter in the next word
}
else{
pigLatWord = word.substr(index);
length = pigLatWord.length();
pigLatWord.insert(length, " ");
pigLatWord.insert(length, 1, word[index]);
pigLatWord.erase(0, 1);
index = word.length();
}
pigLatSentence += (pigLatWord + " ");
}
return pigLatSentence;
}
|