In c# we can use:
function_name("This is test number: " + i);
How can I do it in c++?
Thank you guys
In c# we can use:
function_name("This is test number: " + i);
How can I do it in c++?
Thank you guys
Assuming that function_name
takes an std::string
argument, and you have C++11 support, you can use
function_name("This is test number: " + std::to_string(i));
Actually, if i
were an integer, then string + i
would yield a array shifted by that many elements(assuming this keeps base address in bounds, else garbage data is produced).
So, in your case if i=4
, then your string is passed as " is test number: "
, removing "This"
.
So, if want to concatenate strings you can use above solution using std::string:
function_name("This is test number: " + std::to_string(i));
EDIT: Since you have commented that i
is not int
so this might no more remain valid.
Let;s at first consider the expression
"This is test number: " + i
You want to get some new string that will contain the both operands of the operator +. So this string has to be allocated dynamically in memory. The only standard C++ class that allocates a memory dynamically for strings is std::string
. However it has no operator +
where one of operands has an integral type. So object i has to be converted to an object of type std::string explicitly. It can be done using standard function std::to_string
In this case the call would look as
function_name("This is test number: " + std::to_string( i ) );
However if the function accepts only arguments of type char *
then you can not use class std::string
.
So what do you need?
As I mentioned you have to allocate the character array itself before calling the function. Let assume that you defined such an array that can accomodate the string literal and the number stored in i.
char s[SOME_ENOUGH_SIZE];
When you could write
std::sprintf( s, "&s %i", "This is test number: ", i );
function_name( s );
You could also allocate the array dynamically. For example
char *s = new char[SOME_ENOUGH_SIZE];
and call the function the same way as shown above.