简体   繁体   中英

Join const char with int into a char*

Given this variables:

const char* Filename="file";
int size=100;
int num=300;

I want to put them together in one char* with this format "file_num_size" (file_300_100 in this case), so what in c++ would be as easy as do:

std::string newFile =Filename+std::to_string(size)+std::to_string(num);

How could I do it in C on the var char* newFile; ??

Thanks

--------------EDIT----------------

Thanks to all, I guess not setting a size to the var newFile would be a bit hard to achieve, so i will just go with sprintf and setting a size to newfile. THanks again.

Roughly like this:

const char* Filename="file";
int size = 100;
int num = 300;
char newFile[50];    // buffer for 50 chars
sprintf(newfile, "%s_%d_%d", Filename, num, size);

You need to make sure that the filename is never longer than 49 chars.

If the length of filename can be very long this variant may be better:

const char* Filename="very_long_file_name_fooo_bar_evenlonger_abcde_blabla";
int size = 100;
int num = 300;
char *newFile = malloc(strlen(Filename) + 30);  // computing needed length
sprintf(newfile, "%s_%d_%d", Filename, num, size);
...
free(newFile);    // free the buffer, once you're done with it, but only then

The + 30 is a quick and dirty way to make room for the _xxx_yyy . There is room for improvement here.

If you are using c99 or higher version of C compiler they support variable length arrays, where we can allocate an auto array (on stack) of variable size.

Assuming that size and num are always the positive integers, you can do:

#include <stdio.h>
#include <string.h>

int getSize (int n) {
    int size = 1;
    while (n > 9) {
            n /= 10;
            size++;
    }
    return size;
}

int main()
{
    const char* Filename="file";
    int size = 100;
    int num = 300;

    int total_size = strlen(Filename)+getSize(size)+getSize(num)+1;

    char newFile[total_size]; //Variable length array

    sprintf(newFile, "%s_%d_%d", Filename, num, size);

    printf ("newfile : %s\n", newFile);

    return 0;
}

In compile-time (fastest, but can't be changed):

#define FILE "file"
#define NUM 300
#define SIZE 100

#define STRINGIFY(x) #x
#define NEWFILE(file, num, size) file "_" STRINGIFY(num) "_" STRINGIFY(size)

...
const char* Filename = FILE;
int num = NUM;
int size = SIZE;
const char* newFile = NEWFILE(FILE, NUM, SIZE); // "file_300_100"

In run-time, slow but readable:

sprintf(str, "%s_%d_%d", file, num, size);

(Where str is large enough to contain the result - this has to be checked in advance)

Faster run-time versions do the integer to string conversion manually, then build the string manually step by step.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM