Concatenate strings inside function parameter

Hello, I want to create function which accepts string as parameter and prints it to console, e.g.

1
2
3
4
5
6
7
8
//Usage
print("Hello " + "world");

//Definition
void print(std::string text)
{
    std::cout << text << std::endl;
}


//Output
Hello world

Now I also want to perform things like:

print("Your number is" + 5);

etc.

However, this does not work, error I get is:

error C2110: '+' : cannot add two pointers


I don`t want to do this:

1
2
std::string myText = "Number is " + 5;
print(myText);


This is annoying, I need to do it inside function parameter, is this possible? Thanks.


EDIT: Found out I can do this:

print("This" "is" "working");

But still cannot put number variables inside.
Last edited on
@mutexe I am not sure how can I achieve the above with to_string :)

Since function just won`t accept any concatenation inside parameter print("test " + 5 + "asda" + "sss");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

void printMe(std::string message)
{
	std::cout << message << std::endl;
}


int main()
{
	std::string one("test");
	std::string two("asda");
	std::string three("sss");

	int numberFromUser = 5;

	printMe(one + two + std::to_string(numberFromUser) + three);
	
    return 0;
}
Thanks, but that is still not what I want :D I know I can concatnate it in that way.

I just don`t see myself or the user making 3+ shorthand variables everytime I want to use print() function.

Please, is there anyway how to do it like for example:

1
2
int age= 40;
print("Your have " + 40+ " years");


Really just stupid example but it will get used more and more complex.

EDIT: Found out I can do this:

print("This" "is" "working");

But still cannot put number variables inside.
Last edited on
I'm really not sure what you're after then I'm afraid.
But i do know that passing hard-coded values into a function is not a great idea.
Ok, I am making a game.
Now I will need many prints into console, like print name, fps, position etc.
But doing it like this is really annoying and long

std::cout << "Object with name " << name << " is at x: " << position.x << " y: " << position.y << std::endl;

This was maybe just a simple example, I want to code fast just without always writing std:: and cout and endl over and over.

If this would possible, it would really help out

print("Object with name " + name +" is at x: " + position.x + " y: " position.y);
Last edited on
Topic archived. No new replies allowed.