Error with Tokenizing

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?
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
50
51
52
53
54
55
56
57
58
59
// Luke Simmons Lab 05
#include<iostream>
#include <string>
using namespace 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 while in your printLatinWord function.

you need to remove word++ before while loop.

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.
Last edited on
Topic archived. No new replies allowed.