Pig latin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 string pigLatinString(string originalString){

	string word, newString;
	size_t x = 0, wordLength, stringLength;
	stringLength = originalString.length();

	while (count < stringLength){
	
		stringLength = originalString.length();
                wordLength = originalString.find(" ") - 1;
		if (wordLength = string::npos)
			break;
		word = originalString.substr(x + 1, wordLength) + originalString[x] + "ay ";
		newString += word;
		originalString.erase(x, wordLength + 1);
	}


	return newString;
}


I'm trying to write a function for a program that converts a string(originalString) to pig latin. The main function inputs the string and passes it to this function, and then this function returns the pig latin string(newString). When I run the program it reads in the original string and then prints out a blank line. I've gone through the program line by line to determine what each variable should be and what should be returned and when I do it works out correctly, but not when I run the program. What am I doing wrong?
Guessing count is a global variable somewhere.

 
wordLength = originalString.find(" ") - 1;

You shouldn't really subtract one from this, if it "is" equal to npos it will mess up the function.

1
2
if (wordLength = string::npos)
	break;

This should be == (comparison) not = (assignment). Right now your function is always leaving immediately....I would also expect this check to be at the end of the function not the beginning, what happens if the user enters in 1 word? You might need to design it slightly differently for that.
1
2
3
4
5
6
7
8
9
string ToPigLatin(string text){

        if (!text.empty()) // or (text.length() > 0)
        {
               string tmp = "-" + text[0] + "ay";
               return text.erase(0,1) + tmp;
        }
        return text;
}


I haven't tested it but this might work. I'm not sure is string::erase returns the actual string.
Last edited on
After compiling my code it I forgot that C++ doesn't allow you to concatenate strings and chars as easy as C#. lol

I edited it to work. You can easily use this on a multiword string by passing in each word.

1
2
3
4
5
6
7
8
9
10
11
string ToPigLatin(string text) {

        if (!text.empty()) // or check if it has at least 2 letters if you want)
        {
               string tmp = "-";
               tmp += text[0]; 
               tmp += "ay";
               return text.erase(0,1) + tmp;
        }
        return text;
}
Last edited on
Topic archived. No new replies allowed.