gpt4 book ai didi

C编程: Singular to plural nouns

转载 作者:行者123 更新时间:2023-11-30 14:27:48 38 4
gpt4 key购买 nike

我的程序应该是

编写一个程序,根据以下规则接受名词并形成其复数形式:

  1. 如果名词以“y”结尾,则删除“y”并添加“ies”。
  2. 如果名词以“s”、“c”、“ch”或“sh”结尾,请添加“es”。
  3. 在所有其他情况下,只需添加“s”。

打印每个名词及其复数。

它工作正常,当我输入诸如“dairy”之类的单词时,它会打印“dairies”,但它会循环并打印“dairieseseseseseseseseseseseses...”等等。我希望这是一个我找不到的快速修复方法,有人可以帮助我!

谢谢!

#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;
}

最佳答案

我假设您希望程序在用户输入文本done时终止。如果是这样,您需要修复循环:

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);
}

当前版本将循环,直到 pluralize() 将字符串设置为 done,这永远不会发生。

顺便说一句,您应该使用 strncmp()strncat() 以避免潜在的缓冲区溢出。这在此类代码中并不是太重要,但如果您编写的内容面对不受信任的用户,则可能会使用 strcmp()strcat().

关于C编程: Singular to plural nouns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7247330/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com