Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading