Reputation: 1563
I have a function with default Parameters which displays text to screen. Something like this:
DrawScreenString(int, int, string, int uicolor, font);
I am however trying to pass in a string variable "livesRemaining" like so:
DrawScreenString(10, 5, "Lives : %d ",livesRemaining, 0xF14040, NULL);
livesRemaining = 3
So due to the fact that the function only takes in 5 arguments, it fails to compile, because the function thinks that i'm trying to pass in a 6th argument not knowing i'm trying to add string to the already existing string "Lives :"
This is what i want the result to look like:
Live : 3
I know this is not the right way of doing this, how do i do it ? Thanks a bunch !!
Upvotes: 0
Views: 98
Reputation: 106
If you are using a compiler with c++11 support in it, you can use the to_string method that chris mentioned (http://www.cplusplus.com/reference/string/to_string/?kw=to_string)
DrawScreenString(1,5, "Lives Remaining: " + std::to_string(livesRemaining), 0xF00000, NULL).
However, if your compiler doesn't have the to_string functionality, you can use a stringstream to construct (http://www.cplusplus.com/reference/sstream/stringstream/stringstream/) or sprintf into a char buffer and then constructing the string from a char buffer. I personally don't like the sprintf option because of the fixed buffer and concerns about overflow of the buffer if the input isn't checked, but it is an option.
Edit: Example with stringstream added per OP request:
#include <sstream>
...
std::stringstream ss;
int livesRemaining = 5;
ss << "Lives remaining: " << livesRemaining;
DrawScreenString(1,5, ss.str(), 0xF00000, NULL);
Upvotes: 1
Reputation: 4556
You can append your string "Lives: " to the livesRemaining variable like so:
"Lives : %d :"+Integer.toString(uicolor)
OR
"Lives : %d :"+uicolor + ""
OR
"Lives : %d :"+String.valueOf(uicolor)
Finally, looking like this for example:
DrawScreenString(10, 5,"Lives : %d :"+Integer.toString(uicolor), 0xF14040, NULL);
livesRemaining = 3
Upvotes: 0