Reputation: 13
I am attempting to change the last character in a word to make it the plural version of that word. For example bus to buses or penny to pennies. I get a warning when I try to set the last character equal to the plural ending. Please let me know what I need to change in order to fix this problem. Thank you.
#include <stdio.h>
#include <string.h>
int main(void) {
char word[50];
char *last_char;
printf("Enter a word: ");
scanf("%[^\t\n]", word);
last_char = &word[(strlen(word)-1)];
if(*last_char == 'y')
{
*last_char = "ies";
printf("\nthis does not work %s", word);
}
else if(*last_char == 's')
{
*last_char = "es";
printf("\nthis is working %s", word);
}
else if(*last_char == 'h')
{
*last_char = 'es';
printf("\nPlural: %s", word);
}
else
{
last_char = &word[(strlen(word))];
*last_char = 's';
printf("\nPlural: %s", word);
}
return 0;
}
Upvotes: 0
Views: 850
Reputation: 133948
Just look at what you said yourself:
I get a warning when I try to set the last character equal to the plural ending.
You've got a memory slot for one character at that position and you're trying to squeeze many at that one slot. Isn't going to work.
"ies";
is not a single character, it is a string - an array of characters that decays to a pointer to the first character. A single char
is of integer type; you cannot convert a pointer to character (well you can, but it does not make sense).
In this case the simple solution would be to strcpy
the ending to the subarray starting from last_character
, i.e.:
strcpy(last_char, "ies");
As for
last_char = &word[(strlen(word))];
*last_char = 's';
that is not correct because the string would not be null-terminated!
remember that last_char
was already pointing to the last character, and the null terminator after that is at address last_char + 1
; you can replace these two lines with
strcpy(last_char + 1, "s");
Upvotes: 2