Appending strings in C

前端 未结 6 1847
无人共我
无人共我 2020-12-12 02:21

How do I combine multiple strings. For example,

char item[32];
scanf(\"%s\", item);
printf(\"Shopping list: %s\\n\", item); //I want to combine this string          


        
6条回答
  •  佛祖请我去吃肉
    2020-12-12 03:05

    There are multiple issues I'm about to ignore (sequencing of input and output; error handling for input; buffer overflows on input; single words vs multiple words in an entry, etc), but:

    char item[32];
    scanf("%s", item);
    char hw[32];
    scanf("%s", hw);
    char string_2[] = "To do list: Sleep\n";
    
    printf("Shopping list: %s\n%sHomework: %s\n", item, string_2, hw);
    

    This gives you a single printf() statement that provides the concatenated output. Clearly, the concatenation is on the output file (standard output) and not directly in memory. If you want the strings concatenated in memory, then you have to go through some machinations to ensure there's enough memory to copy into, but you can then use snprintf() for the job instead of printf():

    char item[32];
    scanf("%s", item);
    char hw[32];
    scanf("%s", hw);
    char string_2[] = "To do list: Sleep\n";
    
    // This length does account for two extra newlines and a trailing null
    size_t totlen = strlen(item) + strlen(homework) + sizeof(string_2) +
                    sizeof("Shopping list: ") + sizeof("Homework: ");
    char *conc_string = malloc(totlen);
    
    snprintf(conc_string, totlen, "Shopping list: %s\n%sHomework: %s\n",
             item, string_2, hw);
    

提交回复
热议问题