Search code examples
arraysccs50strcat

doing the no-vowels cs50 problem and ran into an error with strcat


When running my program:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    string word = get_string("Give me a word: " );
    int j = strlen(word);
    int i;
    char new[j + 1];

    new[0] = '\0';
    
    for (i = 0; i < j; i++)
    {
        if (word[i] == 'e')
        {
            strcat(new, "3");
        }
        else if (word[i] == 'i')
        {
            strcat(new, "1");
        }
        else if (word[i] == 'a')
        {
            strcat(new, "6");
        }
        else if (word[i] == 'o')
        {
            strcat(new, "0");
        }
        else
        {
            char p = word[i];
            strcat(new, p);
        }
    }
    printf("%s\n", new);
}

I get the error:

no-vowels-test.c:39:25: error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]
            strcat(new, word[i]);
                        ^~~~~~~
                        &
/usr/include/string.h:149:70: note: passing argument to parameter '__src' here
extern char *strcat (char *__restrict __dest, const char *__restrict __src)

My goal here is to make the last else statement append the current letter in the array of word[i] into the variable new[] to spell out a new word where every vowel is replaced by a number, the numbers I have no problem with. But the last else statement seems to have a problem and I cant figure out why.


Solution

  • The second argument to strcat must be a C string, ie: an array of char terminated with a null byte, not a single char such as p.

    You can fix this problem with strncat: replace strcat(new, p); and the previous line with:

        strncat(new, &word[i], 1);
    

    This concatenates at most 1 char from the string starting at word[i].

    Another approach would set the bytes in new directly:

    #include <cs50.h>
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        string word = get_string("Give me a word: " );
        int i;
        int j = strlen(word);
        char new[j + 1];
    
        for (i = 0; i < j; i++)
        {
            if (word[i] == 'e')
            {
                new[i] = '3';
            }
            else if (word[i] == 'i')
            {
                new[i] = '1';
            }
            else if (word[i] == 'a')
            {
                new[i] = '6';
            }
            else if (word[i] == 'o')
            {
                new[i] = '0';
            }
            else
            {
                new[i] = word[i];
            }
        }
        new[i] = '\0';
        printf("%s\n", new);
    }