-
poiglatin problem?
Greetings,
I am stuck, plks help fix? Any help is appreciated.
Code:
#include <iostream> // cin, cout, <<, >>
#include <string> // class string
using namespace std;
string Piglatin(string englishWord);
int main()
{
cout << "\nTo translate a sentence from English to Pig-latin,\n"
<< " enter a sentence: ";
string englishWord,
piglatinWord;
char separator;
for (;;)
{
cin >> englishWord;
cin.get(separator);
piglatinWord = Piglatin(englishWord);
cout << piglatinWord;
if (separator == '\n')
{
cout << endl;
break;
}
else
cout << ' ';
}
return 0;
}
/*********************************************************
* Piglatin translates a word from English to Pig-latin. *
* Receive: englishWord, a string. *
* Return: piglatinWord, a string. *
*********************************************************/
string Piglatin(string englishWord)
{
int vowelPosition = englishWord.find_first_of("aeiouyAEIOUY", 0);
string lastPart = englishWord.substr(vowelPosition,
englishWord.size() - vowelPosition);
string pigLatinWord = lastPart + firstPart + "ay";
return 0;
}
-
Well, for one thing, you have your Piglatin function returning 0 instead of piglatinWord, that'll screw things up.
-
Couple of other things...
1. Instead of using cin.get() to find the next character, use peek(). get() removes the next character, which is the first character of the next word ("cin >> word" strips the whitespace separator as well).
2. Move the peek to after the calculation and display of the pig latin word. Don't know why this helped but it did.
3. You never calculated firstPart in the Piglatin function.
Your revised code:
Code:
#include <iostream>
#include <string>
using namespace std;
string Piglatin( string );
int main() {
cout << "\nTo translate a sentence from English to Pig-latin,\n"
<< " enter a sentence: ";
string englishWord, piglatinWord;
char separator;
for (;;) {
cin >> englishWord;
piglatinWord = Piglatin( englishWord );
cout << piglatinWord;
separator = cin.peek();
if (separator == '\n') {
cout << endl;
break;
} else {
cout << ' ';
}
}
return 0;
}
string Piglatin( string englishWord ) {
int vowelPosition = englishWord.find_first_of( "aeiouyAEIOUY", 0 );
string firstPart = englishWord.substr( 0, vowelPosition );
string lastPart = englishWord.substr( vowelPosition,
englishWord.size() - vowelPosition);
string pigLatinWord = lastPart + firstPart + "ay";
return pigLatinWord;
}
-
I know it is in C but
Code:
#include <stdio.h>
#include <string.h>
void printLatinWord( char * );
int main()
{
char sentence[ 80 ];
char *tokenPtr;
printf( "Enter a sentence:\n" );
gets( sentence );
printf( "\nThe sentence in Pig Latin is:\n" );
tokenPtr = strtok( sentence, " .,;" );
while ( tokenPtr ) {
printLatinWord( tokenPtr );
tokenPtr = strtok( NULL, " .,;" );
if ( tokenPtr )
printf( " " );
}
printf( "." );
return 0;
}
void printLatinWord( char *word )
{
int i;
for ( i = 1; i < strlen( word ); i++ )
printf( "%c", word[ i ] );
printf( "%c%s", word[ 0 ], "ay" );
}