如何在c++中传递变量Sprintf第二(格式)参数

How to pass variable in C++ Sprintf 2nd(format) argument?

本文关键字:第二 Sprintf 格式 参数 变量 c++      更新时间:2023-10-16

我一直在研究如何在c++中实现这一点:

string format = "what is your %s";  
new_string = sprintf(buffer, format, name);

任何帮助都将非常感激。

谢谢!

使用format.c_str():

string format = "what is your %s";  
int total = sprintf(buffer, format.c_str(), name);

还要注意返回值不是新的字符串,它是缓冲区,它是输出字符串。返回值实际上是写入的字符总数。此计数不包括自动附加在字符串末尾的额外空字符。如果失败,则返回一个负数(参见此处的文档)。

但是在c++中,std::ostringstream是更好的和类型安全的,正如@Joachim在他的回答中解释的。

使用ostringstream:

std::ostringstream os;
os << "what is your " << name;
std::string new_string = os.str();

你可以这样做:

char buffer[100]; 
string format = "what is your %s";
sprintf(buffer, format.c_str(), name.c_str());
string new_string(buffer);

或者,使用stringstream:

stringstream buf;
buf << "what is your " << name;
string new_string = buf.str();

传递给sprintf的格式必须是char*,不能是std::stringsprintf还返回写入的字符数,而不是指向构造缓冲区的指针。

int len = sprintf(buffer, "what is your%s", name);
std::string new_string(buffer, len);
另一种可能是使用std::ostringstream来执行格式化。

我不确定我理解这里的问题- sprintf是一个函数,将char*作为其第一个参数,并将const char*作为其第二个参数。这些都是C数据类型,所以我不知道使用c++字符串是否会被编译器识别为有效。

而且,该函数返回int(写入的字符数),而不是字符串,看起来像您期望的返回值new_string

更多信息,请访问http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

您可以使用c++ STL中的stringstream,这更OO。

查看文档

sprintf是C库的一部分,因此对std::string一无所知。如果你还想使用char*,请使用它。

使用c_str方法从std::string中获取C char*字符串。