Pig Latin Example code
Today
Below is the pig latin example from the first day we discussed it. Please know that it has unresolved issues that we will address next class.
pig.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
// read input
// pig latinify
// - find a vowel
// - reorder and ayify
// write it out
const char *findVowel(const char* word) {
return strpbrk(word, "aeiouAEIOU");
}
void showPig(const char* word) {
const char *vowel = findVowel(word);
printf("%s", vowel); // print the "ig"
fwrite(word, sizeof(char), vowel - word, stdout); // print the "p"
printf("ay"); // print ay
}
int main (int argc, const char *argv[]) {
for (int i = 0; i < argc; i++) {
showPig(argv[i]);
puts("");
}
return 0;
}
Into the Future
Since you might find it helpful, here is the full code of where we’re going with this example, including reading from standard input using read(). We’ll finish this on Friday, but you might find it helpful in wrapping up HW9 or dealing with HW10.
pig.c (Final Version)
#include <stdio.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
// read input
// pig latinify
// - find a vowel
// - reorder and ayify
// write it out
const char *findVowel(const char *word) {
const char *s = strpbrk(word, "aeiouAEIOU");
// Avoid returning NULL from strpbrk if no
// vowel was in the word.
if (s != NULL)
return s;
return word;
}
void showPig(const char *word) {
const char *vowel = findVowel(word);
printf("%s", vowel); // print the "ig"
fwrite(word, sizeof(char), vowel - word, stdout); // print the "p"
printf("ay"); // print ay
}
int main (int argc, const char *argv[]) {
// Stack buffer overflow possibility here!
// We should be VERY CAREFUL and fix this!
// We can only read up to 4095-character words
char buffer[4096];
int index = 0;
// Read from standard in (using read()) one character at a
// time into our buffer at position index (we're reading a
// word).
while(read(0, &buffer[index], 1)) {
if(isalpha(buffer[index])) {
index++; // If current char is a letter, continue to
// collect the word in buffer
} else {
// If not a letter, then we're at a word break and we should
// then handle the word we just finished
// Save the current character in a local variable (so we can
// terminate the string without this current char)
char saveme = buffer[index];
// If our current word is at least 1 character, then overwrite
// the current (non-word) character with the null terminator and
// pass the string to showPig to show the last word in pig latin
if (index > 0) {
buffer[index] = '\0';
showPig(buffer);
}
// Write the non-letter out (the current character that was not
// part of our previous word)
fwrite(&saveme, sizeof(char), 1, stdout);
// Reset the buffer to start reading at the beginning (i.e., start
// a new word!)
index = 0;
}
}
return 0;
}