gpt4 book ai didi

c - 嵌套 if 语句失败

转载 作者:太空宇宙 更新时间:2023-11-04 08:20:44 26 4
gpt4 key购买 nike

我正在尝试设置一个函数来查看文本字符串,并将“y”替换为“ies”以使其成为复数。

我在这里遇到的问题(除了无知)是函数不会进入第一个嵌套 if 语句。 (

char noun_to_plural(char n[10])  
{
int length;
char temp[10];
char replace[10];

length = strlen(n); //This returns 3 correctly when passed "fly"
printf("length is %d\n", length );

if (length == 3 ) //Successfully enters this statement
{
printf("1st Loop Entered\n");
strcpy(temp, &n[length -1]); //correctly retuns "y" for value temp.
printf("Temp value is %s\n", temp);

if (temp == 'y') //It will not pass into this if condition even
//though temp is 'y'
{
printf("2nd Loop Entered");
replace[10] = strcpy(replace, n );
replace[3] = 'i';
replace[4] = 'e';
replace[5] = 's';

printf("Loop entered test-%s-test", n ); //returns string "fly"
}
}
}

最后,是否有更简单的方法将我缺少的“y”更改为“ies”?这个功能显然没有完成,因为我正在努力让它进入第二个条件。我什至尝试使用:

if (strcpy(temp, &n[length -1] == 'y') 

那也没用。

最佳答案

char temp[10];

变量 temp 是一个字符数组, 将衰减为指向第一个元素的指针。

如果你想检查第一个元素(一个字符),你需要像下面这样的东西之一:

if (temp[0] == 'y')
if (*temp == 'y')

就将缓冲区更改为复数而言(尽管你会发现所有奇怪的边缘情况,比如 jockey -> jockeies),这可以通过类似的方式完成:

char buffer[100];
strcpy (buffer, "puppy");

size_t ln = strlen (buffer);
if ((ln > 0) && (buffer[ln-1] == 'y'))
strcpy (&(buffer[ln-1]), "ies");

当然,这是基本思想,更专业的代码将对数组大小运行检查,以确保您不会遇到缓冲区溢出问题。

关于c - 嵌套 if 语句失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33534784/

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