+ 1
Pig Latin solution for C and C++
I solved the Pig Latin problem in Code Coach for Java, C#, and Python. But I am struggling to solve it in C and C++. Here is the C code I tried. It gives the correct output but the unit tests still fail. Can someone please help me to fix my solution or is there a different method to solve this problem? #include <stdio.h> #include <string.h> void main() { char text[20]; scanf("%[^\n]s", text); char* token = strtok(text, " "); while (token != NULL) { for (int i = 0; i < strlen(token); i++) printf("%c", token[i + 1]); printf("%cay", token[0]); token = strtok(NULL, " "); if (token != NULL) printf(" "); } }
4 odpowiedzi
+ 2
I made your code pass the tests with the following changes:
1) Change main to int, not void.
2) The text array is 1 character short of being large enough. Make it 21 or higher.
3) The printf statement in the for loop goes past the end of each word. Change the loop to start at 1 instead of 0 and use [i] instead of [i+1] in the printf.
for (int i = 1; i < strlen(token); i++)
printf("%c", token[i]);
4) add return 0;
+ 3
Tharinda Nimnajith you're welcome. The C++ version is similar, and looks even cleaner. Use cin to parse the words and indicate as well when the input has ended. I'll let you work that out.
+ 2
Thanks Brian
+ 1
I'll take a look. In the meantime, consider this: You can let scanf() parse the words for you. That gives way to a two-line solution.
#include <stdio.h>
#include <string.h>
int main() {
char buf[256];
while (scanf("%s", buf) != EOF)
printf("%s%cay ", buf+1, *buf);
return 0;
}