【问题标题】:nested if statement failing嵌套 if 语句失败
【发布时间】:2015-11-05 00:43:50
【问题描述】:

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

那也没用。

【问题讨论】:

  • 您没有收到if (temp == 'y') 的编译器警告,如下所示?还有replace[10] = strcpy(replace, n );

标签: c string strcpy


【解决方案1】:
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");

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

【讨论】:

  • 有没有办法可以查找编译器警告和错误?例如: [警告] 传递 'strcpy' 的参数 2 使指针从整数而不进行强制转换。
  • @semiprostudent,我会把警告打到谷歌(或你最喜欢的搜索引擎)上,看看有什么反应。最终,您的体验将上升到您将立即认识到这是一个“哦,不,我使用的是字符而不是 C 字符串”问题的水平 :-) 如 strcpy(buffer,'a'); 或类似的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-02
  • 2019-01-26
  • 1970-01-01
  • 2012-06-01
  • 2016-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多