[英]how do you pass in string with a string variable to a function in C++
我有一个带有默认参数的函数,该函数在屏幕上显示文本。 像这样:
DrawScreenString(int, int, string, int uicolor, font);
但是,我试图像这样传递一个字符串变量“ livesRemaining”:
DrawScreenString(10, 5, "Lives : %d ",livesRemaining, 0xF14040, NULL);
livesRemaining = 3
因此,由于该函数仅接受5个参数,因此无法编译,因为该函数认为我正在尝试传递第6个参数,却不知道我正在尝试将字符串添加到已存在的字符串中。 ”
这就是我想要的结果看起来像:
Live : 3
我知道这不是正确的方法,我该怎么做? 谢谢一大堆!
如果您使用的是支持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).
但是,如果您的编译器不具有to_string功能,则可以使用stringstream构造( http://www.cplusplus.com/reference/sstream/stringstream/stringstream/ )或sprintf到char缓冲区中,然后构造来自char缓冲区的字符串。 我个人不喜欢sprintf选项,因为缓冲区固定,并且如果不检查输入,则担心缓冲区溢出,但这是一个选项。
编辑:示例为每个OP请求添加stringstream:
#include <sstream>
...
std::stringstream ss;
int livesRemaining = 5;
ss << "Lives remaining: " << livesRemaining;
DrawScreenString(1,5, ss.str(), 0xF00000, NULL);
您可以将字符串“ Lives:”附加到liveRemaining变量中,如下所示:
"Lives : %d :"+Integer.toString(uicolor)
要么
"Lives : %d :"+uicolor + ""
要么
"Lives : %d :"+String.valueOf(uicolor)
最后,例如:
DrawScreenString(10, 5,"Lives : %d :"+Integer.toString(uicolor), 0xF14040, NULL);
livesRemaining = 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.