0

Is it possible to create array of char from different data types merging it into one char array. char array[32] = "matrix"+a+b+".txt"; E.g:

int main(){
int a = 10;
int b = 10;

char array[32] = "matrix"+a+b+".txt";
return 0;
}

I have tried different ways. But it didn't helped. Thank you!

Jasurbek Nabijonov
  • 1,607
  • 3
  • 24
  • 37

2 Answers2

3

For C, use snprintf():

int a = 10;
int b = 10;

char array[32];

snprintf(array, sizeof(array), "matrix%d%d.txt", a, b);

For C++, use strings instead of character arrays; you can concatenate strings easily since they overload the + operator:

int a = 10;
int b = 10;

std::string str{std::string{"matrix"} + std::to_string(a) + std::to_string(b) + ".txt"};
cdhowie
  • 158,093
  • 24
  • 286
  • 300
1

I think you should firstly understand how a C-string works... a C-String is always an array of chars... but an array of char is not always a C-String.

The "definition" (not a formal definition, but something close to it) is that a C-String contains a sequence of bytes that will represent a string (characters) and the end of the string will be marked with a null-byte (0)

This is a C-String:

char myString[4] = { 'a', 'b', 'c', 0 };

This is NOT a C-String:

char myBuffer[3] = { 'a', 'b', 'c' };

Checking your example... trying to make "matrix"+a+b+".txt" shows that you are actually looking for construct a C-String with different types.

--

So, in order to mix different types of data in order to build a string we have several options...

  • In C: use snprintf()
  • In C++: use std:string or std::ostringstream

There are more options for both, but these above are very common.

The std::string in C++ is NOT a C-String... but can be converted to one with the function .c_str().

Wagner Patriota
  • 5,494
  • 26
  • 49