0

I am trying to set up a function that looks at a string of text, and replaces "y" with "ies" to make it plural.

The problem I am having here (aside from ignorance), is that the function will not enter the 1st nested if statement. (

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"
            }
     }
}

Lastly, is there an easier way to change the 'y' into 'ies' that I am missing? This function isn't complete obviously as I am struggling to get it to go into the 2nd condition. I even tried using:

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

and that didn't work either.

  • Didn't you get a compiler warning for the `if (temp == 'y')` as answered below? And also for `replace[10] = strcpy(replace, n );` – Weather Vane Nov 05 '15 at 00:49

1 Answers1

2
char temp[10];

The variable temp is a character array, which will decay into a pointer to the first element.

If you want to check that first element (a character), you need something like one of the following:

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

In terms of changing a buffer to plural (notwithstanding all the strange edge cases you're going to find, like jockey -> jockeies), this can be done with something like:

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

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

That's the basic idea though, of course, more professional code would be running checks on the array size to ensure you're not subjecting yourself to buffer overflow problems.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Is there a way I can lookup the compiler warnings and errors? For example: [Warning] passing argument 2 of 'strcpy' makes pointer from integer without a cast. – semiprostudent Nov 05 '15 at 00:56
  • @semiprostudent, I would just punch the warning into google (or your favourite search engine) and see what came back. Eventually, your experience will rise to the level where you will *instantly* recognise that as being an "oh, no, I used a character rather than a C string" problem :-) As in `strcpy(buffer,'a');` or something similar. – paxdiablo Nov 05 '15 at 01:20