View Single Post
Old 05-22-2005, 02:13 PM   #2 (permalink)
redhead
Newbie
 
redhead's Avatar
 
Join Date: Jun 2002
Location: Denmark
Posts: 1,720
redhead is on a distinguished road
You've got some errors in your pig latin algorithm, I've made some changes to the program, I hope the comments will explain why those things are made.
Code:
/*Pig Latin*/
/*Valerie*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LINE_LENGTH 80
#define ADDITION "ay"

int translate(char* trans);

int main()
{
  int i = 0, j = 0, wordcount = 0;
  char line[LINE_LENGTH +1];
  char word[LINE_LENGTH +strlen(ADDITION)]; /* make room for ay at the end */
  
  printf("\n\tWelcome to Pig Latin.\n");
  printf("\tPlease enter a sentence you would like to translate\n");
  printf("Real line:\t");
  fflush(stdout);
  fgets(line, LINE_LENGTH, stdin);
  line[strlen(line) -1] = '\0'; /* remove '\n' at the end */
  printf("In pig Latin:\t");
  while (line[i]!='\0')
    {
      /* pick out a single word in the line */
      while (line[i]!= ' ' && line[i] != '.' && line[i] != '\0')
	word[j++] = line[i++];
  
      ++wordcount;
      word[j] = '\0';
      translate(word);
      j = 0;
      if(line[i] == '.')
	break;
      ++i;
      /* make sure extra spaces aren't screwing it up for us */
      while(line[i] == ' '|| line[i] == '\t' || line[i] == '\r')
	++i;
    }
  printf("\nNumber of words translated: %d\n", wordcount);
  printf("\nPress enter to exit\n");
  getchar();
  return 0;
}


int translate (char* trans)    
{
  int i = 0, j = 0;
  char temp1[LINE_LENGTH +1];
  char temp2[LINE_LENGTH +strlen(ADDITION)];
  temp1[0] = '\0';
  temp2[0] = '\0';
  /* pick out the consonants befor any vowel */
  while(trans[i] !='a' && trans[i] !='e' && trans[i] !='i' 
	&& trans[i] !='o' && trans[i] !='u'&& trans[i] !='y')
    temp1[i] = trans[i++];
  temp1[i] = '\0';
  /* copy the rest of the word */
  while(trans[i] != '\0')
    temp2[j++] = trans[i++];
  temp2[j] = '\0';
  /* append the consonants to the word */
  strncat(temp2, temp1, strlen(temp1));
  /* append the ay to the end of the word */
  strncat(temp2, ADDITION, strlen(ADDITION));
  printf("%s ", temp2);

  return 0;
}
Now there are severa things that can be further developed on this, the translate() could be made to take the entire line, and translate one word at a time, then return with the translated part... But then again I'm not sure, where you want to use this.
__________________
Don't worry Ma'am, We're university students, We know what We're doing.
-----
If you pull the pin, Mr.Grenade would no longer be your friend.
-----
01000111 01101111 00100000 01000011 00100000 00100001
redhead is offline   Reply With Quote