如何在c++中传递变量Sprintf第二(格式)参数
How to pass variable in C++ Sprintf 2nd(format) argument?
我一直在研究如何在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::string
。sprintf
还返回写入的字符数,而不是指向构造缓冲区的指针。
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*
字符串。
相关文章:
- 如何从给定字符串中删除第二次和第三次出现的$
- 打印第二列时的2d字符矢量打印空间
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- 等待整个 omp 块完成,然后再调用第二个函数
- 嵌套的 for 循环不循环通过第二个数组
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- 如何在创建自定义迭代器时获得 std::p air 的第一个和第二个?
- 使用 sprintf 将十六进制0xAABBCC转换为字符串"AA:BB:CC"
- WinAPI 在单击第一个对话框上的按钮控件并销毁第一个对话框后创建第二个对话框
- 高精度双精度的 Sprintf 格式化问题
- 如何在不C++排序的情况下找到给定向量中的第一、第二和第三高值?
- 将第二个 GATT 服务添加到 Movesense 容器
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- sprintf(b, "%" ) 是否定义了?
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- getopt_long_only第二次调用时返回 -1
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 使第二个类的构造函数成为第一个类中的友元函数
- 如何在c++中传递变量Sprintf第二(格式)参数