Appending strings in C

前端 未结 6 1842
无人共我
无人共我 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:06

    Consider using the great but unknown open_memstream() function.

    FILE *open_memstream(char **ptr, size_t *sizeloc);

    Example of usage :

    // open the stream
    FILE *stream;
    char *buf;
    size_t len;
    stream = open_memstream(&buf, &len);
    
    // write what you want with fprintf()
    char item[32];
    scanf("%s", item);
    fprintf(stream, "Shopping list: %s\n", item);
    char string_2[] = "To do list: Sleep\n";
    fprintf(stream, "%s\n", string_2);
    char hw[32];
    scanf("%s", hw); 
    fprintf(stream, "Homework: %s\n", hw);
    
    // close the stream, the buffer is allocated and the size is set !
    fclose(stream);
    printf ("the result is '%s' (%d characters)\n", buf, len);
    free(buf);
    

    Let the kernel manage the buffer allocation, it does it better than you !

提交回复
热议问题