Im writing a program to accept a line from the user and translate it into pig latin. The lab requires us to use tokenizing and pointer arithmetic. I have it so it runs, but not in the right order. If I input "Help me" as the line to get translated I get "elp meHay". What am I doing wrong?
// Luke Simmons Lab 05
#include<iostream>
#include <string>
usingnamespace std;
// Prototype for the function
void printLatinWord(char *);
int main()
{
// Declare two variables
char phrase[200];
char *token;
char *token2;
// prompt the user for input
cout << "Enter a phrase to be translated into piglatin: ";
// extract the first token
token = strtok_s(phrase, " ", &token);
// While there are tokens in "string"
while (token != NULL)
{
// read the input from the user
cin.getline(phrase, 200, '\n');
// call the print latin word function
printLatinWord(token);
// insert a blank according to the phrase
cout << " ";
// get the next token
token = strtok_s(NULL, " ", &token);
}
system("pause");
return 0;
}
void printLatinWord(char *word) // prints the pig latin word
{
// sepearate the first letter
char firstletter = *word;
word++;
// print the other letters
while (*word != '\0')
{
cout << *word;
word++;
}
// print the first letter and "ay"
cout << firstletter << "ay";
}
I didn't debug your code, just reading it in browser and I think the problem is word++ before whilein your printLatinWord function.
you need to remove word++ before whileloop.
your while loop starts read second character instead of first one,
so your function should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void printLatinWord(char *word) // prints the pig latin word
{
// sepearate the first letter
char firstletter = *word;
// print the other letters
while (*word != '\0')
{
cout << *word;
word++;
}
// print the first letter and "ay"
cout << firstletter << "ay";
}
edit:
also not related to error but might result in new error later is that you are incrementing a pointer inside function without reseting it to initial position later which might yield bad result if using a pointer later.
consider creating duplicate pointer and increment duplicate instead of original.