#include <stdio.h>
#include <string.h>
void pigLatinConsonant(char input[]) {
char end[] = "ay";
int length = strlen(input);
int first_vowel = -1;
for (int i = 0; i < length; i++) {
if (strchr("aeiou", input[i])) {
first_vowel = i;
break;
}
}
if (first_vowel != -1) {
char consonant_cluster[length + 1];
strncpy(consonant_cluster, input, first_vowel);
consonant_cluster[first_vowel] = '\0';
strcpy(input, input + first_vowel);
strcat(input, consonant_cluster);
}
strcat(input, end);
printf("Translated word: %s\n", input);
}
int main() {
char sentence[100];
printf("Enter a sentence: ");
fgets(sentence, sizeof(sentence), stdin);
char sentence_copy[sizeof(sentence)];
strcpy(sentence_copy, sentence);
char *token = strtok(sentence_copy, " ");
while (token != NULL) {
pigLatinConsonant(token);
token = strtok(NULL, " ");
}
return 0;
}
Here I tried to call this method from the loop but I think it has something to do with how my function is built. The user enters a sentence, it should move the first two characters, and put them at the end of the word and add ay to it.
For starters your code has nothing common with the assignment
This statement
already invokes undefined behavior.
You may not use
strcpywhen ranges are overlapping.Instead you should use
memmove.Also this statement
can overwrite memory outside the original array.
You should allocate a new character array within the function that is gretaer by 3 than the length of the original string and build in it a new string.
if to use a variable length array to store the converted string then the function can look the following way as shown in the demonstration program below
The program output is