开发者

C Programming: Singular to plural nouns

my program here is supposed to

Write a program that takes nouns and forms their plurals on the basis of thee rules:

  1. If noun ends in “y”, remove the “y” and add “ies”.
  2. If noun ends in “s”, “c”, “ch”, or “sh”, add “es” .
  3. In all other cases, just add “s”.

Print each noun and its plural.

It works fine, when I enter word such as dairy it prints dairies, but it loops and prints dairieseseseseseseseseseseses...etcetc. I was hoping this is a quick fix that I can't find and somebody can 开发者_如何学运维help me with it!

Thanks!

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



#define max_word 20



/* prototypes */
void pluralize (char word[]);


int main (void)
{ 
  char noun[max_word];   /* stores temporary word entered by user */

  printf("Enter a noun in singular form: ");
  scanf("%s", noun);

  while (strcmp(noun, "done") != 0)
 {
    pluralize (noun);
    printf("The plural form is %s\n", noun);
 }

  return;
}

void pluralize (char word[])
{
  int length;
  char noun;
  length=1;
  length = strlen(word);

   if (word[length - 1] == 'y') 
 {   word[length - 1] = 'i';
     word[length] = 'e';
    word[length + 1] = 's';
    word[length + 2] = '\0';  
  }


  /* if word ends in "s" "ch" or "sh" add "es" */

 else if (word[length - 1] == 's' ||
    (word[length - 2] == 'c' && word[length - 1] == 'h') ||
    (word[length - 2] == 's' && word[length - 1] == 'h'))
  {  strcat(word, "es");
  }

  else
 {   strcat(word, "s");

    printf("New word is: ", &noun);
} 
return;
}


I assume that you want the program to terminate if the user enters the text done. If so, you need to fix your loop:

for (;;) 
{
    printf("Enter a noun in singular form: ");
    scanf("%s", noun);

    if ((strcmp(noun, "done") == 0)
        break;

    pluralize (noun);
    printf("The plural form is %s\n", noun);
}

The current version will loop until pluralize() sets the string to done, which will never happen.

As a side note, you should be using strncmp() and strncat() to avoid a potential buffer overflow. This is not too important in this kind of code, but if you're ever writing something that faces an untrusted user, you could be opening yourself up to a serious security vulnerability by using strcmp() and strcat().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜