嵌套,如果语句失败

嵌套,如果语句失败

问题描述:

我想设置一个函数,查看一个字符串的文本,并用“我”替换“y”使其复数。嵌套,如果语句失败

我在这里(除了无知)的问题是该函数不会输入第一个嵌套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”,我很想念一个更简单的方法? 因为我努力让它进入第二此功能没有明显的完成。条件I即使使用尝试:

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

并且没有任何工作

+0

难道你没有得到'if(temp =='y')'的编译器警告吗?还有'替换[10] = strcpy(replace,n);' –

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

,虽然是当然的基本理念,更专业的代码将是银行经营对数组大小进行检查,以确保您不会受到缓冲区溢出问题的困扰。

+0

有没有办法查找编译器的警告和错误?例如: [警告]传递'strcpy'的参数2使得整型指针没有强制转换。 – semiprostudent

+0

@semiprostudent,我只是将警告输入谷歌(或您最喜爱的搜索引擎)并查看回来的内容。最终,你的经验将上升到你将立即*认识到的一个“哦,不,我使用了一个字符而不是一个C字符串”的问题:-)和'strcpy(buffer,'a')一样, ;'或类似的东西。 – paxdiablo