0

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 !!

2
  • 1
    I think you're just looking for std::to_string. Commented Apr 10, 2014 at 1:08
  • Please check the question again i just updated it :) Commented Apr 10, 2014 at 1:40

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

The sprintf concerns can die off a little by using snprintf.
Don't know why I didn't think of that, but agreed.
@PatViafore can you please show how you can do this with the stringstream ? as i am very confused as to how it works, Thanks !!
0

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

1 Comment

Please check the question again i just updated it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.