Using strcat in C

后端 未结 7 1693
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 15:50

Okay so I have the following Code which appends a string to another in C#, note that this is Just an example, so giving alternative string concatination met

7条回答
  •  误落风尘
    2020-12-05 16:25

    I wonder why no one mentioned snprintf() from stdio.h yet. That's the C way to output multiple values and you won't even have to convert your primitives to strings beforehand.

    The following example uses a stack allocated fixed-sized buffer. Otherwise, you have to malloc() the buffer (and store its size), which would make it possible to realloc() on overflow...

    char buffer[1024];
    int len = snprintf(buffer, sizeof(buffer), "%s %i", "a string", 5);
    if(len < 0 || len >= sizeof(buffer))
    {
        // buffer too small or error
    }
    

    Edit: You might also consider using the asprintf() function. It's a widely available GNU extension and part of TR 24731-2 (which means it might make it into the next C standard). The example from above would read

    char * buffer;
    if(asprintf(&buffer, "%s %i", "a string", 5) < 0)
    {
        // (allocation?) error
    }
    

    Remember to free() the buffer when done using it!

提交回复
热议问题