嵌套if语句失败

时间:2015-11-05 00:43:50

标签: c string strcpy

我正在尝试设置一个查看文本字符串的函数,并将“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') 

这也不起作用。

1 个答案:

答案 0 :(得分:2)

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

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

相关问题