cstringcharcs50strcat

How do I concat a character into a string?


I'm trying to take a char and add it to a string. OR if that's not possible, add it to an array of characters?

I tried changed 'string updated = ""' to 'char updated[text_length]' but I was getting the same error - incompatible integer to pointer conversion error

if(argc == 2 && IsDigitsOnly(argv[argc-1])) {
    // convert to integer
    int x = atoi(argv[argc-1]);

    // prompt user for plaintext
    string plaintext = get_string("plaintext: ");
    int text_length = strlen(plaintext);
    int ascii = 'a';
    string updated= "";


    for (int i = 0; i < text_length; i++)
    {
        if (isalpha(plaintext[i]))
        {
            if (isupper(plaintext[i]))
            {
                // GETTING ERROR HERE -- trying to pass 'letter' in strcat
                // This gives me an error: incompatible integer to pointer conversion error
                int n = (plaintext[i] + x) % 90;
                char letter = n;
                strcat(updated, letter);
            }
            else
            {
                ascii = (ascii + x) % 122;
            }
        }
    }

    printf("%s\n", updated);
} 

Solution

  • Based on the string and get_string() call, I assume that you are using cs50. In this case:

    1. You can not write to a string literal (updated).

    2. srtcat wants a pointer to char (not a char) as second parameter.

    Switch to:

    char updated[SOME_SIZE] = "";
    ...
    char letter = n;
    strcat(updated, (char[]){letter, 0});
    

    Notice that strcat is prone to buffer overflows, consider replacing it with snprintf, something like:

    char updated[SOME_SIZE] = "";
    ...
    char letter = n;
    size_t len = strlen(updated);
    
    snprintf(updated + len, sizeof updated - len, "%c", letter);