简体   繁体   English

如何将带有字符串变量的字符串传递给C ++中的函数

[英]how do you pass in string with a string variable to a function in C++

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: 但是,我试图像这样传递一个字符串变量“ livesRemaining”:

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 :" 因此,由于该函数仅接受5个参数,因此无法编译,因为该函数认为我正在尝试传递第6个参数,却不知道我正在尝试将字符串添加到已存在的字符串中。 ”

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 !! 谢谢一大堆!

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 ) 如果您使用的是支持c ++ 11的编译器,则可以使用chris提到的to_string方法( 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. 但是,如果您的编译器不具有to_string功能,则可以使用stringstream构造( http://www.cplusplus.com/reference/sstream/stringstream/stringstream/ )或sprintf到char缓冲区中,然后构造来自char缓冲区的字符串。 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. 我个人不喜欢sprintf选项,因为缓冲区固定,并且如果不检查输入,则担心缓冲区溢出,但这是一个选项。

Edit: Example with stringstream added per OP request: 编辑:示例为每个OP请求添加stringstream:

#include <sstream>
...
std::stringstream ss;
int livesRemaining = 5;
ss << "Lives remaining: " << livesRemaining;
DrawScreenString(1,5, ss.str(), 0xF00000, NULL);

You can append your string "Lives: " to the livesRemaining variable like so: 您可以将字符串“ Lives:”附加到liveRemaining变量中,如下所示:

"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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM